开发者

validation of special characters

I want to validate login name with special characters !@#S%^*()+_-?/<>:"';. space using regular expression in ruby on rails. These special characters should not be开发者_StackOverflow中文版 acceptable. What is the code for that?


validates_format_of :username, :with => /^[A-Za-z0-9.&]*\z/

will work


You've received regexps in this thread that answer your specific question. You're doing a black-list approach (blocking the characters you don't want) but is this really what's best? I see you didn't cover & or ~, and there are many other special characters that are likely still missing.

If you're trying to block special characters, I'd suggest a white-list approach, as per pablorc's regexp suggestion. It's far more broad and lists only what you want to allow....non-special characters: only words, underscore and numbers.

I've gone ahead and created a method for you that does a white-list approach using this regexp.

def valid_login?(str)
    return true if (/^\w*$/.match(str))
    return false
end

This method, valid_login?, returns true only if the string contains letters, numbers, or underscore, so all of your special characters (plus any other you've left out that do not meet these requirements), are safely detected.

Usage:

> valid_login?("testy") 
  true
> valid_login?("a b")
  false
> valid_login?("a'")
  false


Well I don't know rails but this is what the regex would look like in every other language I know:

^[^!@#\$%\^\*\(\)\+_\-\?/\<\>:"';\. ]$


The regex /^\w*$/ allows to use only letters, numbers, and a underscore.

Also, you have a cheatsheet and a live ruby regexp editor on http://rubular.com


First off, I would recommend using a gem for login, like authlogic.

The gem can be configured to validate the email address. You also get the benefit of not having to worry about authenticating your users, etc.

Very easy gem to work with too.


validates_format_of :username, :with => /^[^!@#S%\^\*()\+_-\?\/<>:\"';]+$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜