Bijendra
Bijendra

Reputation: 10025

Validation of data for certain specific special characters

I want to add validations to my rails application. I have added in my model,

validates_format_of :description, :with => /^[a-zA-Z\d ]*$/i,:message =>
 "can only contain letters and numbers." 

But now I want some specific special characters (like for ex- :) to be allowed.

How would I add them?

Upvotes: 1

Views: 1423

Answers (3)

Wes
Wes

Reputation: 6585

Sounds like you want all standard word characters (I know you haven't mentioned underscore explicitly) in addition to spaces and colon:

/^[\w\s:]*$/

Upvotes: 0

ndp
ndp

Reputation: 21996

Just add them to your regular expression inside the square brackets. To add a colon:

/^[a-zA-Z\d :]*$/

Be careful, though, there are a few special characters that need to be escaped with a backslash: . | ( ) [ ] { } + \ ^ $ * ?. To add a period to your set, use:

/^[a-zA-Z\d \.]*$/

Upvotes: 2

Jon Gauthier
Jon Gauthier

Reputation: 25582

You can add them into the regex you have:

validates_format_of :description, :with => /^[a-zA-Z\d\s:]*$/i,:message =>
 "can only contain letters and numbers."

(I changed the literal whitespace character in your regular expression to a \s escape as well.)

Upvotes: 1

Related Questions