Rails,控制器中的字母数字验证

时间:2011-09-25 20:50:18

标签: ruby-on-rails ruby regex ruby-on-rails-3

在我的应用中,我让用户选择一个用户名,就像推特注册页面一样:https://twitter.com/signup

当用户开始输入用户名时,我希望实时让用户知道用户名是否可用&有效的。

我用来验证用户名的正则表达式是字母数字是:

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

给定params[:username]

在控制器中,如何验证用户名是否为字母数字。注意,我不是在这里保存记录只是验证。所以模型验证不起作用。

想法?感谢

3 个答案:

答案 0 :(得分:6)

您仍然希望使用模型验证。

或许这样的事情:

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

答案 1 :(得分:1)

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

unless your_string.match(r).nil?
  # validation succeeded
end

答案 2 :(得分:1)

我认为您的正则表达式有点过于冗长。我实际上会尝试以下正则表达式进行字母数字验证:

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