skip to content

In a Rails youth-sports Player model, which built-in validators enforce a username format and an age from 6 to 18, and what traps hide in them?

level: middleimportance: should knowfreq 55%

answer

  1. format: with \A and \z
  2. ^ or $ raises ArgumentError
  3. numericality reads the raw input
  4. inclusion or numericality in: 6..18
  5. presence fails on false

basics

~20 s

Use format: { with: /\A[a-z0-9_]+\z/ } and length: { in: 3..20 } for the username, numericality: { only_integer: true, in: 6..18 } for age, and comparison: for dates; ^ or $ in a format regex raises, and presence rejects false.

solid answer

~50 s

For the username, `validates :username, format: { with: /\A[a-z0-9_]+\z/ }, length: { in: 3..20 }`. Rails raises `ArgumentError` when the regex starts with `^` or ends with `$` unless you pass `multiline: true`, because those anchors match per line and let `"ok\n<script>"` through. For age, `numericality: { only_integer: true, in: 6..18 }` checks the value **before type cast**, so `"abc"` gives "is not a number" instead of being judged as the `0` an integer column casts it to; `inclusion: { in: 6..18 }` works too but reports only "is not included in the list". For dates, `comparison: { greater_than_or_equal_to: :season_cutoff }` compares against a method or lambda. Two more traps: `presence: true` on a boolean rejects `false` (use `inclusion: { in: [true, false] }`), and most validators fail on `nil` unless you add `allow_nil: true`.

code

ruby · 11 lines
ruby
class Player < ApplicationRecord
  # raises ArgumentError when the class loads: ^ and $ are line anchors
  # validates :username, format: { with: /^[a-z0-9_]+$/ }

  validates :username, format: { with: /\A[a-z0-9_]+\z/ }, length: { in: 3..20 }
  validates :age, numericality: { only_integer: true, in: 6..18 }
end

player = Player.new(username: "coach_amy", age: "abc")
player.valid?
player.errors[:age] # => ["is not a number"]

go deeper

for a junior

Recall the everyday validators (presence, length, format, numericality, inclusion) and their main options.

for a middle

Explain the anchor guard in format, numericality's raw-value check, presence on booleans and allow_nil versus allow_blank.

for a senior

Express cross-field rules with comparison and method names, and keep error types stable for clients while messages stay translatable.

for a principal

Decide which value rules are duplicated as database check constraints so imports and bulk writes cannot bypass them.

## The rules for a league registration A youth-sports league registers players with a username (3 to 20 lowercase letters, digits or underscores), an age between 6 and 18, a birth date after the division's cutoff, and a `photo_consent` boolean. Rails' built-in validators cover all of it: ```ruby class Player < ApplicationRecord validates :username, format: { with: /\A[a-z0-9_]+\z/ }, length: { in: 3..20 } validates :age, numericality: { only_integer: true, in: 6..18 } validates :birth_date, comparison: { greater_than_or_equal_to: :division_cutoff } validates :photo_consent, inclusion: { in: [true, false] } end ``` ## The validators and their main options | Validator | Key options | Default error type | |---|---|---| | `presence` | (none) | `:blank` | | `length` | `minimum`, `maximum`, `in`/`within`, `is` | `:too_short`, `:too_long`, `:wrong_length` | | `format` | `with` or `without`, `multiline` | `:invalid` | | `numericality` | `only_integer`, `greater_than`(`_or_equal_to`), `less_than`(`_or_equal_to`), `equal_to`, `other_than`, `in`, `odd`, `even` | `:not_a_number`, `:not_an_integer`, the comparison name | | `inclusion` / `exclusion` | `in`/`within` (array, range, proc or method) | `:inclusion` / `:exclusion` | | `comparison` | `greater_than`, `less_than`, `equal_to`, `other_than` and the `_or_equal_to` forms | the comparison name | Every validator also takes the shared options `message:`, `allow_nil:`, `allow_blank:`, `on:`, `if:`, `unless:` and `strict:`. ## Trap 1: line anchors in format In Ruby, `^` and `$` match at the start and end of **any line**. `/^[a-z0-9_]+$/` therefore accepts `"coach_amy\n<script>alert(1)</script>"`: the first line matches. Rails guards this: a `format:` regex whose source starts with `^` or ends with `$` makes the validator raise `ArgumentError` when the class loads, unless you pass `multiline: true`. Use `\A` and `\z`, which anchor the whole string. ## Trap 2: numericality and type casting An integer column casts `"abc"` with `String#to_i`, giving `0`. If you only checked the cast value, garbage input would look like an age of zero. `numericality` inspects the value **before type cast** for user input, so `"abc"` reports `is not a number` and `"12.5"` with `only_integer: true` reports `must be an integer`. That is the reason to prefer it over `inclusion: { in: 6..18 }` for numbers: the messages say what was wrong. `numericality` also fails on `nil` unless you add `allow_nil: true`. ## Trap 3: presence on booleans `presence` uses `blank?`, and `false.blank?` is `true`. So `validates :photo_consent, presence: true` rejects a player who answered **no**. Validate a boolean with `inclusion: { in: [true, false] }` (or `exclusion: { in: [nil] }`). ## Comparison for dates and cross-field rules `comparison` compares the attribute with a value, a lambda or a **method name**: `greater_than_or_equal_to: :division_cutoff` calls `division_cutoff` on the record at validation time. That makes cross-field rules (`end_date` after `start_date`, birth date after a cutoff) declarative instead of hand-written. ## allow_nil versus allow_blank - `allow_nil: true` skips the validator when the value is `nil`. - `allow_blank: true` also skips it for `""` and whitespace-only strings. - An optional field usually wants one of them; a required field gets `presence` plus the format rule. ## Messages Each validator adds an error **type** (`:too_short`, `:not_a_number`) with interpolation values such as `count`. The English text comes from locale files: "is too short (minimum is 3 characters)", "must be in 6..18". Override with `message:` or translations; branch in code on the type. ## Choosing between numericality, inclusion and comparison | Need | Prefer | Why | |---|---|---| | a whole number in a range | `numericality: { only_integer: true, in: 6..18 }` | reports not-a-number and not-an-integer separately | | one of a fixed set of values | `inclusion: { in: %w[U8 U10 U12] }` | the set is the rule | | a date or value relative to another field | `comparison: { greater_than: :start_on }` | resolves a method or lambda per record | | a pattern | `format: { with: /\A...\z/ }` | anchors the whole string | Custom text per rule goes in `message:`, either a string or a symbol looked up in the locale files. Keep the error **type** stable even when the text changes, because forms, APIs and tests are easier to keep correct when they test types rather than sentences.

  • Why does validates :photo_consent, presence: true reject a player whose answer is false?
    `presence` checks `blank?`, and in Rails `false.blank?` is `true`, so a legitimate `false` fails as if the field were empty. Use `inclusion: { in: [true, false] }` to require an answer either way.
  • When would inclusion: { in: 6..18 } be a worse choice than numericality for age?
    With `inclusion`, a non-numeric input is first cast (`"abc"` becomes `0`) and reported only as "is not included in the list". `numericality` reads the raw input and says "is not a number" or "must be an integer", and supports `only_integer:` and per-bound messages.

  • Writing format: { with: /^[a-z0-9]+$/ } and expecting Rails to accept it silently.
  • Validating a boolean flag with presence: true.
  • Assuming numericality passes nil without allow_nil: true.
  • Saying length: { in: 3..20 } also checks which characters are allowed.
  • Using allow_blank: true on a field that must be present.