Search code examples
ruby-on-railsregexdevisebrakeman

Regex, devise & brakeman. Ruby on rails 5.2.2


I'm using the given regex expression to validate the username:

validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true

By running brakeman gem i'm having the following warning.

== Warnings ==

Confidence: High
Category: Format Validation
Check: ValidationRegex
Message: Insufficient validation for `username` using `/^[a-zA-Z0-9_\.]*$/`. Use `\A` and `\z` as anchors
File: app/models/user.rb
Line: 16

What would be the optimal regex expression to correctly assign those anchors and keeping the same character permissions?

Regex is yet a myth for me! Best regards.


Solution

  • From ruby on rails guides regular expressions

    To fix the regular expression, \A and \z should be used instead of ^ and $, like

    /\A[a-zA-Z0-9_\.]*\z/