Home > Enterprise >  Allow users to enter letters and numbers only in Rails
Allow users to enter letters and numbers only in Rails

Time:09-08

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.

CodePudding user response:

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.

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.

CodePudding user response:

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:]]/
  • Related