I've never been much of a regex wrangler, and learning rails at the
same time isn't helping.
I want to create a validation that fails if a user tries to create a
username with spaces. But I can't seem to get the right
validates_format_of regex going.
While I think that your regex is smokin’ hot, I do think you might be better served [at least on the error messages front] by two validations there:
validates_format_of :username, :with => /[1][a-z0-9A-Z]*$/, :message => “can only contain letters and numbers” # Or something
validates_length_of, :minimum => 2, :maximum => 10, :too_short => “must be at least 2 characters”, :too_long => “cannot be longer than 10 characters”
that way you’ll have separate error messages for each problem rather than having to lump them all in together. You way does work though. I’m just trying to offer a helpful hint.
I agree and my model already had a validates_length_of so I modified
the proposed regex to eliminate the length check.
Discussing this with my partner we decided to allow numbers, letters,
and underscore (_) so I am going to try the regex
/^[a-zA-Z0-9_]*$/
We don't care if the first character is a letter, number, or
underscore, only that these are the only characters allowed anywhere
in the username. So "_username", "user_name", and "1user_name" should
all be valid.
Think this should work? I don't have access to the site to test it
until I get home tonight.
I had never noticed that validates_length_of supports two error
messages, one for too short, and one for too long. I'll have to
implement that in my code tonight as well.
Now if I could only find a non-ugly way to sort the error messages so
they match the order of the form fields I'd be all set.