class Assent::Validate
Public Class Methods
new(field, value, rules, errors)
click to toggle source
# File lib/assent/validations/validator.rb, line 8 def initialize(field, value, rules, errors) @field = field @value = value @rules = rules @errors = errors end
Public Instance Methods
validate()
click to toggle source
Validate
method that checks all the validations for a single field
# File lib/assent/validations/validator.rb, line 15 def validate required accepted return if blank? date ip @errors end
Private Instance Methods
accepted()
click to toggle source
Validates if a field has the value true, 1 or yes
Example: class TermsValidator < Assent::Validator
field :terms, accepted: true
end
# File lib/assent/validations/validator.rb, line 54 def accepted validation(:accepted) { @value == true || @value == 1} end
blank?()
click to toggle source
Checks if the given value is nil or empty
# File lib/assent/validations/validator.rb, line 87 def blank? @value.nil? || @value.empty? end
date()
click to toggle source
Validates if a field is a valid date
Example: class RegistrationValidator < Assent::validator field :date, date: true end
# File lib/assent/validations/validator.rb, line 64 def date validation(:date) do |validator| date = Date.parse(@value) rescue nil !date.nil? end end
ip()
click to toggle source
Validates if a field is a valid ip-address
Example: class IpValidator < Assent::Validator
field :ip, ip: true
end
# File lib/assent/validations/validator.rb, line 78 def ip validation(:ip) do |validator| result = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/.match(@value.to_s) !result.nil? end end
required()
click to toggle source
Validates the presence of a field
Example:
class LoginValidator < Assent::Validator
field :email, presence: true
end
credentials = Hash.new credentials = nil LoginValidator.new.errors will contain errors because of a nil value
credentials = “test@example.com” This will pass
# File lib/assent/validations/validator.rb, line 44 def required validation(:presence) { !blank? } end
validation(rule) { |validator)| ... }
click to toggle source
# File lib/assent/validations/validator.rb, line 91 def validation(rule) validator = @rules[rule] if(validator) && (!yield validator) @errors.add(@field, rule) end yield validator end