1

I'm setting up a user form in Rails that requires a first name and last name. I decided to use the 3rd to last regular expression from the this Ruby doc to ensure that they don't enter any numbers or special characters. Unfortunately when I return to the form I get this error:

The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?.

I'm just beginning to learn RegEx so if there's a better way to write this validation I'm all ears.

Code:

validates :first_name, :last_name, length: {minimum: 2}, format: {with: /^([^\d\W]|[-])*$/, message: 'First Name/Last Name cannot have any numbers or special characters'}
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • The warning is quite explicit. It tells you that you're using anchors for start and end of line on a multiline regex without saying it will work on singleline where the `\A` is prefered over `^` and `\z` is preferred over `$` in single line check. so with a regex of the form `/\A([^\d\W]|[-])*\z/` it would work, you may test this at http://regex101.com which give you explanation on the anchors/parts of regex. – Tensibai Oct 08 '14 at 11:55
  • See http://guides.rubyonrails.org/security.html#regular-expressions for an explanation – Stefan Oct 08 '14 at 11:55

2 Answers2

4

The documentation you linked to states:

Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.

Since you don't need multiline support for names (i.e. newlines in the name should be regarded invalid), you can safely change this to:

/\A([^\d\W]|[-])*\Z/

See also this answer which explains the security risk a bit more.

Community
  • 1
  • 1
awendt
  • 13,195
  • 5
  • 48
  • 66
1

You will need to use \A for start of line and \z for end of line instead of ^ and $ due to security reasons. So your regexp should be

/\A([^\d\W]|[-])*\z/
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34