你仍然想使用模型驗證。
像這樣的東西可能:
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
的正則表達式應該使用\ A和\ z與代替^和$。 (http://answers.oreilly.com/topic/280-how-to-validate-urls-with-regular-expressions/) – mahemoff