I have a user registration page. I want user password to be from 4 to 16 symbols. I need to check that they have at least one uppercase letter and 1 digit. Than I am making md5 hash of this password and put it into database.
How do I validate it?
Validation in model tests if password is 32symbols length:
validates :password, :length => { :minimum => 32 ,
:message => 'Not an md5 password provided.' }
But how do I validate that password matches my requirements before making a hash of it and set appropriate errors for this validation?
I would like view to get user.errors[:password] containing something like 'Must have at least one digit.' and 'Must have at least one uppercase letter.'
You can create a custom validator method where you can do whatever you want:
validate :password_validation
def password_validation
unless password.length > 32 && ... # other requirements
errors.add(:password, 'Not an md5 password provided.')
end
end
You can provide custom callbacks. See this link from the Rails guide: http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-validators
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.