Skip to content

Instantly share code, notes, and snippets.

@maxschulze
Created November 30, 2012 19:22
Show Gist options
  • Save maxschulze/4177915 to your computer and use it in GitHub Desktop.
Save maxschulze/4177915 to your computer and use it in GitHub Desktop.
class Credentials
include Support::Base
attribute :password, String
attribute :password_confirmation, String
with_options allow_blank: true do |v|
v.validates :password, confirmation: { message: proc{ error_msg(:password, :passwords_dont_match) } }
v.validates :password, length: { minimum: 8, maximum: 50, message: proc{ error_msg(:password, :invalid) } }
# v.validates :password, format: { with: /[^[:alpha:]]/ }
v.validates :password, format: { with: /^.*[a-zA-Z].*\d.*|.*\d.*[a-zA-Z].*$/ }
end
validates :password, :password_confirmation, presence: true
def valid?(context=nil)
super (context || {})
end
private
def validate(context=nil)
unless password.blank? || password_confirmation.blank?
errors.add(:password, :cannot_match_email) if password == context[:email]
errors.add(:password, :password_has_spaces) if password.strip != password
# loic: i'm not sure if it's =~ or ~= and if it's if or unless, please just try it out
# this way all the other validations can run before yours
if errors[:password].blank? # no errors yet
# now do the big final check
errors.add(:password, :invalid) unless password =~ /^.*[a-zA-Z].*\d.*|.*\d.*[a-zA-Z].*$/
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment