Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression that calls string "a?c" invalid?

In my user model, I have an attribute called "nickname" and validates as such:

validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true

However, it is currently letting this string pass as valid:

a?c

I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.

like image 612
Allan L. Avatar asked Nov 27 '22 19:11

Allan L.


2 Answers

That will match true if the string ends with a valid character. No validation on anything in the middle. Try this:

^[a-zA-Z0-9]*$
like image 171
Joel Coehoorn Avatar answered Dec 05 '22 17:12

Joel Coehoorn


You need to anchor the pattern on both sides:

/^[a-zA-Z0-9]+$/
like image 30
Robert Gamble Avatar answered Dec 05 '22 16:12

Robert Gamble