Reputation: 217
I want to validate login name with special characters !@#S%^*()+_-?/<>:"';
. space using regular expression in ruby on rails. These special characters should not be acceptable. What is the code for that?
Upvotes: 4
Views: 6713
Reputation: 225
If you want to support non-ASCII characters in an allow-list approach you could use POSIX bracket expressions and do something like this:
def valid_login?(str) # word characters and " "
return !! (/^([[[:word:]] ]*)$/.match(str))
end
There are a bunch of other bracket expressions, too, see this documentation: https://ruby-doc.org/3.2.1/Regexp.html#class-Regexp-label-Character+Classes
BONUS: Here's my rubular permalink: https://rubular.com/r/DpSjYbwGC5Vwa5
Upvotes: 0
Reputation: 467
validates_format_of :username, :with => /^[^!@#S%\^\*()\+_-\?\/<>:\"';]+$/
Upvotes: 0
Reputation: 217
validates_format_of :username, :with => /^[A-Za-z0-9.&]*\z/
will work
Upvotes: 9
Reputation: 495
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
Upvotes: 5
Reputation: 950
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
Upvotes: 1
Reputation: 109397
Well I don't know rails but this is what the regex would look like in every other language I know:
^[^!@#\$%\^\*\(\)\+_\-\?/\<\>:"';\. ]$
Upvotes: 1