views:

36

answers:

2

Looking for a Rails validation that will only allow 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."
A: 
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/

Niklaos
Yea, that works! that link looks great, makes me want to learn the most confusing syntax ever!
Sam
This will also match empty strings (you can change the * to a + to match strings of at least one char).
Joshua Smith
This matches underscores, and `\w` already matches numbers so you don't need `\d`.
Beerlington
Thanks guys deed some see any possible breach now ?
Niklaos
A: 

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
Beerlington
Thanks. Didn't realize underscore was in there
Sam