I'm trying to implement a validation in a model like this.
validates_format_of :field, with: /[0-9]/, message: 'must have at least one number (0-9)'
Brakeman detects this a Format Validation
security issue and it recommends to add the anchors between the regular expression.
Insufficient validation for 'field' using /[0-9]/. Use \A and \z as anchors near line 54
If I add those anchors, the regular expression stops working, so I don't know what to do in this case. Here's the tests I made using rails c
.
"asdf1234".match(/\A[0-9]\z/) # => nil
"foobar1".match(/\A[0-9]\z/) # => nil
I need that the method return #<MatchData "1">
in both cases.
Any ideas? Thanks.
If you need to match a string that has at least 1 digit inside, and any other chars before and after, you may use
/\A[^0-9]*[0-9].*\z/m
or just
/\A.*[0-9].*\z/m
Details
\A
- start of string[^0-9]*
- zero or more chars other than an ASCII digit[0-9]
- an ASCII digit.*
- any 0+ chars, as many as possible, up to the\z
- end of string.The m
modifier makes .
match any char, including a line break char.
Actually, /\A.*[0-9].*\z/m
will be a bit slower, as the first .*
will grab all the string at once and then will backtrack to find the last digit. The first one is more optimized.