简体   繁体   中英

Rails validates with regex is not working?

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." }

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.

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 /^[az]*$/ /\\A[az]*\\z/ it will only match a string that contains all lower case letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM