开发者

Rails Validations, number + letters + spaces

Looking for a Rails validation that will only a开发者_StackOverflow中文版llow letters, numbers, and spaces. This will do letters and numbers, but no spaces. I need spaces.

validates_format_of :name, :with => /^\w+$/i,
:message => "can only contain letters and numbers."


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

Here is only Number, Letters ans spaces.

Is that exactly what you need ?

PS : This tools is very useful if you are doing a lot of reg-exp : http://rubular.com/


This is one way:

validates :name, format: { with: /\A[a-zA-Z0-9\s]+\z/i, message: "can only contain letters and numbers." }

Have a nice day.


If you only want letters, numbers, and spaces, but not underscores, the accepted answer won't work for you. The following also won't allow empty strings, but it wouldn't matter either way if the rails model has validates_presence_of :name

/^[a-z0-9 ]+$/i
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜