Bird
Raised Fist0
Ruby on Railsframework~10 mins

Custom validation methods in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom validation methods
Start: Model instance created
↓
Call validate method
↓
Run custom validation method
↓
Check condition inside method
↓
No error
↓
Validation result
↓
Save or reject model
When saving a model, Rails calls custom validation methods that check conditions and add errors if needed, deciding if the model is valid.
Execution Sample
Ruby on Rails
class User < ApplicationRecord
  validate :email_must_be_company

  def email_must_be_company
    unless email&.end_with?('@company.com')
      errors.add(:email, 'must be a company email')
    end
  end
end
This code checks if a user's email ends with '@company.com' and adds an error if it doesn't.
Execution Table
StepActionCondition CheckedResultErrors Added
1Create User instance with email 'user@gmail.com'N/AInstance createdNone
2Call validate method on UserN/ACustom validation method calledNone
3Check if email ends with '@company.com'email = 'user@gmail.com'FalseAdd error: 'email must be a company email'
4Validation resultErrors present?YesUser invalid, save rejected
5Create User instance with email 'employee@company.com'N/AInstance createdNone
6Call validate method on UserN/ACustom validation method calledNone
7Check if email ends with '@company.com'email = 'employee@company.com'TrueNo error added
8Validation resultErrors present?NoUser valid, save allowed
💡 Validation stops after checking condition; errors determine if save proceeds.
Variable Tracker
VariableStartAfter Step 3After Step 7Final
emailN/A'user@gmail.com''employee@company.com'Depends on instance
errorsEmptyContains error for emailEmptyDepends on instance
validation_resultN/AInvalidValidDepends on instance
Key Moments - 2 Insights
Why does the validation fail for 'user@gmail.com' but pass for 'employee@company.com'?
Because the custom method checks if the email ends with '@company.com'. At step 3, 'user@gmail.com' fails this check and adds an error, while at step 7, 'employee@company.com' passes and adds no error.
What happens if the email is nil or empty?
The method uses safe navigation (&.) to avoid errors. If email is nil, the condition returns false, so an error is added, preventing save.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what error is added at step 3?
A'email cannot be blank'
B'email is invalid format'
C'email must be a company email'
DNo error added
💡 Hint
Check the 'Errors Added' column at step 3 in the execution table.
At which step does the validation method confirm the email is valid?
AStep 7
BStep 3
CStep 4
DStep 8
💡 Hint
Look for the step where the condition is true and no errors are added.
If the email was 'admin@company.org', what would happen at step 3?
ANo error added, validation passes
BError added, validation fails
CMethod raises an exception
DValidation skipped
💡 Hint
The method checks if email ends with '@company.com'; 'admin@company.org' does not.
Concept Snapshot
Custom validation methods in Rails let you add your own checks inside models.
Define a method that adds errors if conditions fail.
Use 'validate :method_name' to run it during validation.
If errors are added, the model is invalid and won't save.
Use safe checks to avoid errors with nil values.
Full Transcript
In Rails, custom validation methods let you check specific rules for your model data. When you save a model, Rails calls these methods. Inside the method, you check a condition, like if an email ends with '@company.com'. If it doesn't, you add an error message. This error stops the model from saving. For example, if a user has 'user@gmail.com', the validation adds an error and save fails. But if the email is 'employee@company.com', no error is added and save succeeds. This process helps keep your data clean and correct.

Practice

(1/5)
1. What is the main purpose of a custom validation method in a Rails model?
easy
A. To add your own rules for checking data before saving
B. To automatically generate database tables
C. To create user interface elements
D. To speed up database queries

Solution

  1. Step 1: Understand validation role in Rails

    Validations check data correctness before saving to the database.
  2. Step 2: Identify custom validation purpose

    Custom validations let you write your own rules beyond built-in checks.
  3. Final Answer:

    To add your own rules for checking data before saving -> Option A
  4. Quick Check:

    Custom validation = custom data rules [OK]
Hint: Custom validations add your own data rules [OK]
Common Mistakes:
  • Confusing validations with database setup
  • Thinking validations create UI elements
  • Assuming validations improve query speed
2. Which is the correct way to add a custom validation method named check_age in a Rails model?
easy
A. validates :check_age
B. validate :check_age
C. validate_check_age
D. validates_with :check_age

Solution

  1. Step 1: Recall syntax for custom validations

    Use validate :method_name to call a custom method.
  2. Step 2: Match method name with syntax

    For method check_age, syntax is validate :check_age.
  3. Final Answer:

    validate :check_age -> Option B
  4. Quick Check:

    Custom validation syntax = validate :method_name [OK]
Hint: Use 'validate :method_name' for custom validations [OK]
Common Mistakes:
  • Using 'validates' instead of 'validate' for custom methods
  • Adding underscores in method call
  • Using 'validates_with' incorrectly
3. Given this model code:
class User < ApplicationRecord
  validate :check_name

  def check_name
    errors.add(:name, "can't be blank") if name.blank?
  end
end

What happens if you try to save a User with name = ''?
medium
A. The save fails with an error on the name attribute
B. The save succeeds without errors
C. A syntax error occurs
D. The save fails but no error message is added

Solution

  1. Step 1: Understand the custom validation logic

    The method adds an error if name.blank? is true (empty string).
  2. Step 2: Effect on saving a User with empty name

    Since name is blank, error is added and save fails.
  3. Final Answer:

    The save fails with an error on the name attribute -> Option A
  4. Quick Check:

    Blank name triggers error = save fails [OK]
Hint: Blank fields trigger errors in custom validations [OK]
Common Mistakes:
  • Assuming save succeeds despite errors
  • Confusing blank? with nil check
  • Expecting syntax errors from valid code
4. Identify the error in this custom validation method:
class Product < ApplicationRecord
  validate :check_price

  def check_price
    errors.add(:price, "must be positive") if price <= 0
  end
end
medium
A. The method name should start with 'validate_'
B. The validation should use 'validates' instead of 'validate'
C. No error; the code is correct
D. The comparison operator should be '==' instead of '<='

Solution

  1. Step 1: Check method naming and usage

    Custom validation methods do not need 'validate_' prefix; 'validate :method' is correct.
  2. Step 2: Verify validation logic and syntax

    Using 'validate' with method and condition 'price <= 0' is valid Ruby and Rails syntax.
  3. Final Answer:

    No error; the code is correct -> Option C
  4. Quick Check:

    Custom validation syntax and logic are correct [OK]
Hint: Custom validation methods do not need special prefixes [OK]
Common Mistakes:
  • Adding 'validate_' prefix to method name
  • Using 'validates' for custom methods
  • Changing correct comparison operators
5. You want to create a custom validation that ensures a User's username is at least 5 characters and contains no spaces. Which code correctly implements this?
hard
A.
validate :username_rules

def username_rules
  errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ")
end
B.
validates :username, length: { minimum: 5 }, format: { without: /\s/ }
C.
validate :username_rules

def username_rules
  errors.add(:username, "invalid") unless username.length >= 5 && !username.include:(" ")
end
D.
validate :username_rules

def username_rules
  if username.length < 5 || username.include?(" ")
    errors.add(:username, "must be 5+ chars and no spaces")
  end
end

Solution

  1. Step 1: Understand the validation requirements

    Username must be at least 5 characters and contain no spaces.
  2. 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
    end
    uses OR logic to add error if username is shorter than 5 or contains spaces, which matches requirements.
  3. 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:(" ")
    end
    has syntax error with colon in method call.
    validate :username_rules
    
    def username_rules
      errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ")
    end
    uses wrong comparison (<= 5 excludes 5).
  4. 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 D
  5. Quick Check:

    Custom validation logic matches requirements [OK]
Hint: Check logic carefully: use OR for combined invalid conditions [OK]
Common Mistakes:
  • Using AND instead of OR for combined conditions
  • Confusing built-in validations with custom methods
  • Wrong comparison operators causing off-by-one errors
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