0
0
Ruby on Railsframework~5 mins

Format validation in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is format validation in Rails?
Format validation checks if a model attribute matches a specific pattern, usually using regular expressions, to ensure data is in the correct form.
Click to reveal answer
beginner
How do you add a format validation to a Rails model attribute?
Use validates :attribute, format: { with: /regex/, message: 'error message' } inside the model to enforce a pattern.
Click to reveal answer
beginner
Why use format validation instead of just presence validation?
Presence validation only checks if a value exists, but format validation ensures the value follows a specific pattern, like an email or phone number format.
Click to reveal answer
intermediate
Example: Validate an email format in a Rails model.
Use validates :email, format: { with: URI::MailTo::EMAIL_REGEXP, message: 'must be a valid email' } to check email format.
Click to reveal answer
beginner
What happens if a format validation fails when saving a Rails model?
The model will not save, and the error message defined in the validation will be added to the model's errors, which can be shown to the user.
Click to reveal answer
Which method is used to add format validation in a Rails model?
Avalidate_format_of :attribute
Bcheck_format :attribute, regex
Cvalidates :attribute, format: { with: /regex/ }
Dformat_validation :attribute
What does the with option specify in format validation?
AThe error message to show
BThe regular expression pattern to match
CThe attribute name
DThe validation context
If a format validation fails, what happens when you try to save the model?
AThe model does not save and adds errors
BThe model saves without validation
CThe model saves but logs a warning
DThe model saves and ignores the format
Which built-in regex can you use to validate emails in Rails?
A/\A[^@]+@[^@]+\z/
BEMAIL_VALIDATOR
C/email_regex/
DURI::MailTo::EMAIL_REGEXP
Can format validation be used to check phone number patterns?
AYes, by providing a suitable regex
BNo, only emails are supported
COnly numeric validations are allowed
DFormat validation is not for phone numbers
Explain how to add a format validation to a Rails model attribute and why it is useful.
Think about how you tell Rails to check a pattern for an attribute.
You got /4 concepts.
    Describe what happens when a format validation fails during model saving in Rails.
    Consider the flow of validation and saving.
    You got /4 concepts.