Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, Alphanumeric validation in the controller

In my app I let users select a username, just like the twitter signup page: https://twitter.com/signup

When the user starts typing a username, I want in real-time to let the user know if the username is available & valid.

The regex I've been using to validate the username is alphanumeric is:

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

Given params[:username]

In the controller, how can I validate if the username is alphanumeric or not. Note, I'm not saving the record here just validation. so a model validation wouldn't work.

Ideas? Thanks

like image 513
AnApprentice Avatar asked Feb 22 '23 21:02

AnApprentice


2 Answers

You'd still want to use model validations.

Something like this perhaps:

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
like image 99
numbers1311407 Avatar answered Mar 02 '23 20:03

numbers1311407


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

unless your_string.match(r).nil?
  # validation succeeded
end
like image 24
Adam Eberlin Avatar answered Mar 02 '23 19:03

Adam Eberlin