Validation Flashcards
How to add validation on presence?
validates :name, presence: true
How to validate that value is blank?
validates :name, absence: true
How to check that record is valid? or invalid?
- User.new(name: ‘a’).valid?
- User.new(name: ‘a’).invalid?
How to show a list of errors?
u = User.new(name: ‘a’)
u. valid?
u. errors
How to validate acceptance of the field? ( accept the agreement or not)
validates :terms_of_service, acceptance: true
User.new(terms_of_service: 0).valid? # false
How to validate record formate with regexp?
validates :name, format: { with: /[a-z]/ }
How to check that value is included in the given array?
validates :name, inclusion: { in: [‘a’, ‘b’] }
How to validate length of the record?
validates :name, length: { minimum: 10, maximum: 20 }
How to validate that value is a number?
validates :name, numericality: true
What is the difference between validates and validate?
- “validate” for custom validation
- “validates” for rails validation
How to add a custom validation?
validate :custom_validation
def custom_validation errors.add(:name, 'custom_error') if true end
How to validate that value is unique?
validates :name, uniqueness: true