Allow users to enter letters and numbers only in Rails

Viewed 49

I want to use this regular expression /^[a-zA-Z0-9 ]*$/

But with the condition:

  • The word must start with a letter and not with a number
  • Do not allow special characters

I have tried use another method /[a-z]*$/i but it doesn't seem working. Any help will be really helpful.

3 Answers

You can re-vamp the regex to

/\A(?:[a-zA-Z][a-zA-Z0-9 ]*)?\z/

If the space is a special char, remove it from the regex.

Note that in Ruby, start of string is matched with \A and end of string is matched with \z.

See the Rubular demo.

Details:

  • \A - start of string
  • (?:[a-zA-Z][a-zA-Z0-9 ]*)? - an optional sequence of
  • [a-zA-Z] - an ASCII letter
  • [a-zA-Z0-9 ]* - zero or more spaces, ASCII letters or digits
  • \z - end of string.

Great answer already, although I'd change the whole a-zA-Z thing to just an a-z with a i flag on the regex, just more concise.

Another alternative, which I personally find a bit more expressive, is to use something like:

str.starts_with? /[a-z]/i and not str.match /[^a-z0-9]/i

And finally, I wonder if you'd like to also allow non-ASCII alphabetic characters, like a é or whatever? In which case you'd want to use [:alpha:] and [:alnum:] like this:

str.starts_with? /[[:alpha:]]/ and not str.match /[^[:alnum:]]/

You could also use a negative lookahead to assert not a digit or space at the start of the string.

Using a case insensitive match:

re = /\A(?:[a-zA-Z][a-zA-Z0-9 ]*)?\z/i

Explanation

  • \A Start of string
  • (?![\d ]) Negative lookahead, assert not either a space or digit directly to the right
  • [a-z\d ]* Optionally repeat matching any of the listed
  • \z End of string

See a regex rubular demo.

Related