user352974
user352974

Reputation: 217

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 acceptable. What is the code for that?

Upvotes: 4

Views: 6713

Answers (7)

skiggety
skiggety

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

Shimaa Marzouk
Shimaa Marzouk

Reputation: 467

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

Upvotes: 0

user352974
user352974

Reputation: 217

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

will work

Upvotes: 9

Andres
Andres

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

pablorc
pablorc

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

Kip
Kip

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

cbrulak
cbrulak

Reputation: 15629

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.

Upvotes: 0

Related Questions