In Rails 3, I would like to see if a value for an attribute is valid using the model’s validates options without trying to save or create.
I’m writing the back end of a AJAX API, that should check a username against the
validates :username, :length => {:minimum => 2, :maximum => 50}, :exclusion => {:in => RESERVED_USERNAMES}, :format => MY_REGEX, .etc
In the User model. This it to create a little tick or cross next to the username field in the register form, so the user doesn’t have to wait to see if the username is taken or not.
I could just compare it to a regex, but to try to keep my code DRY, I thought it would be better to use the validation in the user model.
Anyone know how I could do something of the line of:
username = params[:username]
if User.not_found(:username => username) && User.validate(:username => username)
#yay!
else
#nope
end
(I already have the not_found working).
You could try checking for specific errors related to the username, in addition to running all validations (you need to in order to get the error messages).
You can run that without persisting your user to the database, since none of the methods used (including #new and #valid?) actually save the object.