Is the regular expression that calls the string "a? C" invalid?

In my user model, I have the attribute "nickname" and is checked as such:

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

However, this string is currently passed as valid:

a? WITH

I only want to accept alphanumeric strings - does anyone know why my regex doesn't work? If anyone can offer a better regex, I'm all ears.

+4
source share
2 answers

You need to bind the template on both sides:

/^[a-zA-Z0-9]+$/ 
+10
source

This will be true if the string ends with a valid character. No check for anything in the middle. Try the following:

 ^[a-zA-Z0-9]*$ 
+17
source

Source: https://habr.com/ru/post/1277745/


All Articles