I want a rails model to exclude certain patterns: runs of two or more spaces.
User.name = "Harry Junior Potter" is valid, but User.name = "Harry Junior Potter" is not (two spaces between Harry and Junior).
This to avoid identity theft, where those two names are displayed the same (HTML compresses runs of whitespace).
In other words: Allowed is: [0-9A-z_-] and ‘\s only in series of one’.
My regular-expression is too poor to craft such a regexp, this is what I have (with a negative lookahead, but it does not match correctly.
/([0-9A-z_\-])(\s(?!\s))?/
Note: a before_validation hook already strip()s all the elements, so spaces at begin or end of the string are not a problem.
First off,
[A-z]is an error. It’s equivalent to…and I’m pretty sure that’s not what you had in mind. You have to spell out the two ranges separately:
[A-Za-z]. But in this case you’re also matching digits and underscore, so you can use\wlike @Sjuul did:[\w-]+. That makes your regexOf course, that will match silly things like
-- - ---, and it won’t match a lot of real names. I’m just answering your question about allowing only a single space between names.