2

Simple regex is not working.. For example first_name = "a11" works fine. Why isn't my format regex validating properly?

  validates :first_name, presence: { message:  "Name cannot be blank." },
                         format: { with: /[a-z]/i, message:  "Name must only contain letters." },
                         length: { minimum: 2, message:  "Name must be at least 2 letters." }
MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

2 Answers2

6

Because it matches with you regex.

You have to specify the begin and end of the string, and add * or it will just match one char.

format: { with: /\A[a-z]*\z/i, message:  "Name must only contain letters." },

Also note don't use ^ and $, in ruby, ^ and $ matches the begin and end of a line, not the string, so it will be broken on multiline strings.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Your regex returns a match. It's looking for any letter that's present anywhere in the string and returns that match. You want to specify that only letters are allowed.

Update Original answer insecure: https://stackoverflow.com/a/17760113/836205

If you change it to /^[a-z]*$/ /\A[a-z]*\z/ it will only match a string that contains all lower case letters.

Community
  • 1
  • 1
agmin
  • 8,948
  • 2
  • 21
  • 27
  • Your regex is invalid. It causes a security risk on rails. `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?` – MrPizzaFace Jun 26 '14 at 03:51
  • Ah, hadn't run into that before, thanks. It's valid but insecure. A good explanation: http://stackoverflow.com/a/17760113/836205 – agmin Jun 26 '14 at 04:07