Bird
Raised Fist0
Ruby on Railsframework~20 mins

Format validation in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Format Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Rails model with format validation receives invalid input?
Consider a Rails model with this validation:
validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email" }

What will be the state of the model after assigning user.email = "invalid-email" and calling user.valid??
Ruby on Rails
class User < ApplicationRecord
  validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email" }
end

user = User.new
user.email = "invalid-email"
valid = user.valid?
AThe model is valid; errors will be empty because format validation only checks presence.
BThe model is valid; format validation ignores invalid emails without @ symbol.
CThe model raises a runtime error due to invalid regex in validation.
DThe model is invalid; user.errors will include "email must be a valid email".
Attempts:
2 left
💡 Hint
Think about what happens when the input does not match the regex pattern.
📝 Syntax
intermediate
2:00remaining
Which format validation syntax is correct in Rails?
You want to validate that a username contains only letters and numbers. Which of these validations is syntactically correct?
Avalidates :username, format: { regex: /\A[a-zA-Z0-9]+\z/ }
Bvalidates_format_of :username, with: /\A[a-zA-Z0-9]+\z/, message: 'only letters and numbers allowed'
Cvalidates :username, format: { with: /\A[a-zA-Z0-9]+\z/ }
Dvalidates :username, format: /\A[a-zA-Z0-9]+\z/
Attempts:
2 left
💡 Hint
Check the correct key name inside the format hash.
🔧 Debug
advanced
2:00remaining
Why does this format validation not work as expected?
Given this model validation:
validates :phone, format: { with: /\d{3}-\d{3}-\d{4}/ }

Why might a phone number like "123-456-7890" still be invalid?
AThe regex is missing start (\A) and end (\z) anchors, so it matches substrings but validation expects full match.
BThe regex lacks anchors, so partial matches pass, but full string match is required.
CThe regex is correct; the problem is the phone attribute is nil.
DThe format validation requires the regex to be a string, not a Regexp object.
Attempts:
2 left
💡 Hint
Think about how Rails uses the regex to validate the entire attribute string.
❓ state_output
advanced
2:00remaining
What is the value of errors after invalid format validation?
Given this code:
class User < ApplicationRecord
  validates :zip_code, format: { with: /\A\d{5}\z/, message: 'must be 5 digits' }
end

user = User.new(zip_code: '1234a')
user.valid?
errors = user.errors[:zip_code]

What is the value of errors?
A["must be 5 digits"]
B["is invalid"]
C[]
Dnil
Attempts:
2 left
💡 Hint
Check the custom message in the validation.
🧠 Conceptual
expert
2:00remaining
Why use format validation instead of custom validation method in Rails?
Which is the main advantage of using validates :attribute, format: { with: /regex/ } over writing a custom validate :method_name method for format checking?
AFormat validation allows multiple regex patterns at once, custom methods do not.
BFormat validation integrates automatically with Rails error messages and helpers, reducing boilerplate code.
CCustom validation methods cannot add errors to the model.
DCustom validation methods run faster than format validations.
Attempts:
2 left
💡 Hint
Think about how Rails helpers and error messages work with built-in validations.

Practice

(1/5)
1. What is the main purpose of format validation in Rails models?
easy
A. To ensure data matches a specific pattern using regular expressions
B. To check if a field is present and not empty
C. To verify numerical values are within a range
D. To automatically format dates for display

Solution

  1. Step 1: Understand format validation role

    Format validation uses regular expressions to check if data fits a pattern.
  2. Step 2: Compare with other validations

    Presence validation checks if data exists, numericality checks numbers, and formatting dates is unrelated.
  3. Final Answer:

    To ensure data matches a specific pattern using regular expressions -> Option A
  4. Quick Check:

    Format validation = pattern check [OK]
Hint: Format validation = pattern matching with regex [OK]
Common Mistakes:
  • Confusing format validation with presence validation
  • Thinking format validation changes data format
  • Mixing format validation with numerical range checks
2. Which of the following is the correct syntax to validate an email format in a Rails model?
easy
A. validates_format_of :email, with: /\A[^@\s]+@[^@\s]+\z/
B. validate :email, format: /\A[^@\s]+@[^@\s]+\z/
C. validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ }
D. validates :email, regex: /\A[^@\s]+@[^@\s]+\z/

Solution

  1. Step 1: Identify correct validation method

    Rails uses validates with format: { with: REGEX } syntax for format validation.
  2. Step 2: Check syntax correctness

    validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ } correctly uses validates :email, format: { with: /regex/ }. validate :email, format: /\A[^@\s]+@[^@\s]+\z/ uses wrong method validate. validates_format_of :email, with: /\A[^@\s]+@[^@\s]+\z/ uses deprecated validates_format_of. validates :email, regex: /\A[^@\s]+@[^@\s]+\z/ uses invalid key regex.
  3. Final Answer:

    validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ } -> Option C
  4. Quick Check:

    Correct syntax = validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/ } [OK]
Hint: Use validates with format: { with: regex } [OK]
Common Mistakes:
  • Using validate instead of validates
  • Using invalid keys like regex instead of format
  • Using deprecated validates_format_of method
3. Given this model validation:
validates :username, format: { with: /\A[a-z0-9_]+\z/, message: "only allows lowercase letters, numbers, and underscores" }

What happens if you try to save username = "User123"?
medium
A. The record saves successfully
B. The record fails to save with a format error
C. The record saves but the username is changed to lowercase
D. A syntax error occurs

Solution

  1. Step 1: Analyze the regex pattern

    The regex /\A[a-z0-9_]+\z/ allows only lowercase letters, digits, and underscores from start to end.
  2. Step 2: Check the input against the pattern

    Input "User123" contains uppercase 'U', which does not match the pattern.
  3. Final Answer:

    The record fails to save with a format error -> Option B
  4. Quick Check:

    Uppercase breaks regex = validation fails [OK]
Hint: Regex is case sensitive; uppercase breaks lowercase-only pattern [OK]
Common Mistakes:
  • Assuming validation auto-changes case
  • Thinking uppercase letters are allowed
  • Confusing syntax error with validation failure
4. Identify the error in this validation code:
validates :phone, format: { with: /\d{10}/, message: "must be 10 digits" }
medium
A. The regex does not anchor start and end, allowing invalid matches
B. The regex should be enclosed in quotes
C. The message key is misspelled
D. The validates method is missing a colon before phone

Solution

  1. Step 1: Review the regex pattern

    The regex /\d{10}/ matches any 10 digits anywhere in the string, not necessarily the whole string.
  2. Step 2: Understand validation implications

    Without anchors \A and \z, strings with extra characters before or after 10 digits will pass incorrectly.
  3. Final Answer:

    The regex does not anchor start and end, allowing invalid matches -> Option A
  4. Quick Check:

    Regex anchors needed for exact match [OK]
Hint: Always anchor regex with \A and \z for full string match [OK]
Common Mistakes:
  • Forgetting to anchor regex start/end
  • Assuming regex in quotes is required
  • Misspelling keys like message or validates
5. You want to validate a postal code that must be exactly 5 digits or 5 digits followed by a dash and 4 digits (like '12345' or '12345-6789'). Which validation is correct?
hard
A. validates :postal_code, format: { with: /\A\d{5}-\d{4}\z/, message: "invalid postal code" }
B. validates :postal_code, format: { with: /\d{5}(-\d{4})?/, message: "invalid postal code" }
C. validates :postal_code, format: { with: /\A\d{9}\z/, message: "invalid postal code" }
D. validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" }

Solution

  1. Step 1: Understand the postal code formats

    Valid formats are 5 digits alone or 5 digits plus dash and 4 digits.
  2. Step 2: Analyze regex options

    validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } uses anchors \A and \z and allows 5 digits with optional dash and 4 digits. validates :postal_code, format: { with: /\d{5}(-\d{4})?/, message: "invalid postal code" } lacks anchors, allowing partial matches. validates :postal_code, format: { with: /\A\d{5}-\d{4}\z/, message: "invalid postal code" } requires dash and 4 digits always, disallowing 5-digit only. validates :postal_code, format: { with: /\A\d{9}\z/, message: "invalid postal code" } requires exactly 9 digits, no dash.
  3. Final Answer:

    validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } -> Option D
  4. Quick Check:

    Anchored regex with optional group = validates :postal_code, format: { with: /\A\d{5}(-\d{4})?\z/, message: "invalid postal code" } [OK]
Hint: Use anchors and optional group for flexible exact match [OK]
Common Mistakes:
  • Omitting anchors causing partial matches
  • Forcing dash and extra digits when optional
  • Using wrong digit counts or missing optional group
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard