2011-09-25 42 views
4

在我的應用我讓用戶選擇一個用戶名,就像Twitter的註冊頁面:https://twitter.com/signupRails中,控制器字母數字驗證

當用戶開始輸入一個用戶名,我想在實時讓用戶知道用戶名是否可用&有效。

正則表達式我一直在使用,以驗證用戶名是字母數字是:

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

鑑於params[:username]

在控制器中,我如何可以驗證用戶名是否字母或沒有。請注意,我並沒有在這裏保存記錄只是驗證。所以模型驗證將不起作用。

想法?謝謝

+0

的正則表達式應該使用\ A和\ z與代替^和$。 (http://answers.oreilly.com/topic/280-how-to-validate-urls-with-regular-expressions/) – mahemoff

回答

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 
+0

謝謝,但這並不奏效。錯誤總是零。你不需要真正保存以獲取錯誤嗎? – AnApprentice

+0

對不起,在第一次迭代中,我忽略了對'user.valid?'的調用,這是必要的。我在編輯中添加了它。 – numbers1311407

+0

非常好。謝謝!有沒有辦法找回第一個錯誤? – AnApprentice

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

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