开发者

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?


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 \.]*$/


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.)


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

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜