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." }
3
  • What are trying to do? Commented Jun 26, 2014 at 3:45
  • See the regex? [a-z] only. But it doesn't validate. e.g. a329394 does not throw error. Commented Jun 26, 2014 at 3:47
  • @ff15 try [0-9a]+ or [0-9a-z]+ Commented Jun 26, 2014 at 3:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Still not working... Palm to face! Wtf? How can I debug this? Any thoughts because this is just weird.
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.

2 Comments

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?
Ah, hadn't run into that before, thanks. It's valid but insecure. A good explanation: stackoverflow.com/a/17760113/836205

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.