Custom validation methods let you check if your data is correct in ways built-in checks can't. They help keep your app's information clean and reliable.
Custom validation methods in Ruby on Rails
class ModelName < ApplicationRecord validate :custom_validation_method def custom_validation_method if some_condition_is_not_met errors.add(:attribute_name, "custom error message") end end end
The method name after validate is your custom check.
Use errors.add to add an error message to a specific attribute.
class User < ApplicationRecord validate :must_be_adult def must_be_adult if age.present? && age.to_i < 18 errors.add(:age, "must be at least 18 years old") end end end
class Product < ApplicationRecord validate :price_must_be_positive def price_must_be_positive errors.add(:price, "must be greater than zero") if price.to_f <= 0 end end
class Booking < ApplicationRecord validate :start_date_before_end_date def start_date_before_end_date if start_date.present? && end_date.present? && start_date > end_date errors.add(:start_date, "must be before end date") end end end
This Event model checks that the name is not empty and starts with a capital letter. The example creates an event with a lowercase name and shows the validation errors.
class Event < ApplicationRecord validate :name_cannot_be_blank_and_must_start_with_capital def name_cannot_be_blank_and_must_start_with_capital if name.blank? errors.add(:name, "can't be blank") elsif name[0] != name[0].upcase errors.add(:name, "must start with a capital letter") end end end # Example usage: event = Event.new(name: "party") valid = event.valid? errors = event.errors.full_messages puts "Is event valid? #{valid}" puts "Errors: #{errors.join(', ')}"
Custom validations run when you call valid? or try to save the record.
Always add errors to the errors object to stop saving invalid data.
You can add errors to specific attributes or to the base object for general errors.
Custom validation methods let you write your own rules for data checks.
Use validate :method_name and define the method to add errors.
This keeps your app's data clean and your validation logic clear.
Practice
Solution
Step 1: Understand validation role in Rails
Validations check data correctness before saving to the database.Step 2: Identify custom validation purpose
Custom validations let you write your own rules beyond built-in checks.Final Answer:
To add your own rules for checking data before saving -> Option AQuick Check:
Custom validation = custom data rules [OK]
- Confusing validations with database setup
- Thinking validations create UI elements
- Assuming validations improve query speed
check_age in a Rails model?Solution
Step 1: Recall syntax for custom validations
Usevalidate :method_nameto call a custom method.Step 2: Match method name with syntax
For methodcheck_age, syntax isvalidate :check_age.Final Answer:
validate :check_age -> Option BQuick Check:
Custom validation syntax = validate :method_name [OK]
- Using 'validates' instead of 'validate' for custom methods
- Adding underscores in method call
- Using 'validates_with' incorrectly
class User < ApplicationRecord
validate :check_name
def check_name
errors.add(:name, "can't be blank") if name.blank?
end
endWhat happens if you try to save a User with
name = ''?Solution
Step 1: Understand the custom validation logic
The method adds an error ifname.blank?is true (empty string).Step 2: Effect on saving a User with empty name
Since name is blank, error is added and save fails.Final Answer:
The save fails with an error on the name attribute -> Option AQuick Check:
Blank name triggers error = save fails [OK]
- Assuming save succeeds despite errors
- Confusing blank? with nil check
- Expecting syntax errors from valid code
class Product < ApplicationRecord
validate :check_price
def check_price
errors.add(:price, "must be positive") if price <= 0
end
endSolution
Step 1: Check method naming and usage
Custom validation methods do not need 'validate_' prefix; 'validate :method' is correct.Step 2: Verify validation logic and syntax
Using 'validate' with method and condition 'price <= 0' is valid Ruby and Rails syntax.Final Answer:
No error; the code is correct -> Option CQuick Check:
Custom validation syntax and logic are correct [OK]
- Adding 'validate_' prefix to method name
- Using 'validates' for custom methods
- Changing correct comparison operators
username is at least 5 characters and contains no spaces. Which code correctly implements this?Solution
Step 1: Understand the validation requirements
Username must be at least 5 characters and contain no spaces.Step 2: Analyze each option's logic
validate :username_rules def username_rules if username.length < 5 || username.include?(" ") errors.add(:username, "must be 5+ chars and no spaces") end enduses OR logic to add error if username is shorter than 5 or contains spaces, which matches requirements.Step 3: Check other options
validates :username, length: { minimum: 5 }, format: { without: /\s/ }uses built-in validations, not custom method.validate :username_rules def username_rules errors.add(:username, "invalid") unless username.length >= 5 && !username.include:(" ") endhas syntax error with colon in method call.validate :username_rules def username_rules errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ") enduses wrong comparison (<= 5 excludes 5).Final Answer:
validate :username_rules def username_rules if username.length < 5 || username.include?(" ") errors.add(:username, "must be 5+ chars and no spaces") end end -> Option DQuick Check:
Custom validation logic matches requirements [OK]
- Using AND instead of OR for combined conditions
- Confusing built-in validations with custom methods
- Wrong comparison operators causing off-by-one errors
Ready to prove it?
Pass the test and this pattern moves unknown
