Alfo
Alfo

Reputation: 4819

Validate Attribute without saving

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).

Upvotes: 1

Views: 3340

Answers (2)

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

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).

@user = User.new(params[:user])
if @user.invalid? && @user.errors[:username].any?
  # yay!
else
  # nope
end

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.

Upvotes: 2

rjurado01
rjurado01

Reputation: 5535

You can create new user with username param and then inspect errors:

@user = User.new( :username => params[:username] )
@user.valid?    

if @user.errors.include? :username
  # username error
end

Upvotes: 0

Related Questions