Rails, alphanumeric validation in the controller

In my application, I allow users to choose a username, as well as the twitter registration page: https://twitter.com/signup

When the user starts to enter the username, I want to tell the user in real time whether the username is accessible and valid.

The regular expression that I used to validate the username is alphanumeric:

/^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i 

Given params[:username]

In the controller, how can I check if the username is alphanumeric or not. Note that I am not saving the entry here just for verification. therefore, model validation will not work.

Ideas? Thanks

+4
source share
3 answers

You still want to use model checks.

Something like this is possible:

 class User validates :username, :format => { :with => /your regex/ }, :uniqueness => true end # then in some controller action or rack app def test_username user = User.new(:username => params[:username]) # Call user.valid? to trigger the validations, then test to see if there are # any on username, which is all you're concerned about here. # # If there are errors, they'd be returned so you can use them in the view, # if not, just return success or something. # if !user.valid? && user.errors[:username].any? render :json => { :success => false, :errors => user.errors[:username] } else render :json => { :success => true } end end 
+6
source
 r = /^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i unless your_string.match(r).nil? # validation succeeded end 
+1
source

I think your regex is a bit verbose. I would actually try the following regular expression for alphanumeric validation:

 /\A[A-Z0-9]+\z/i 
+1
source

All Articles