9

How can I validate :title in my model so that only the letters a-z, A-z, and 0-9 are accepted?

  validates :title, :format => { with: REGULAR EXPRESSION , :message => 'no special characters, only letters and numbers' }

What should the regular expression be?

1
  • Oh I see I missed that :D
    – Dalorzo
    Jun 4, 2014 at 15:22

1 Answer 1

12

The regular expression would be /^[a-zA-Z0-9]*$/

You basically define three ranges of symbols that are allowed, first a-z, then A-Z and finally 0-9.

The asterisk in the end then defines that zero or more of the previously stated characters need to be matched, that means that an empty title would be allowed. If you want at least one character, use a + instead of the *. Or if you want more than three characters, use {3,} instead of the asterisk.

13
  • 1
    Wouldn't this validate an empty title? Jun 4, 2014 at 15:23
  • 1
    Yes it would. You could replace the asterisk by a + to enforce at least one character. Jun 4, 2014 at 15:24
  • 1
    Your regex could be simplified to /\w/: rubular.com/r/7kA4JHjwD4 --- I would allow the spaces too (your regexp does not catch it): /(\w|\s)/
    – MrYoshiji
    Jun 4, 2014 at 15:28
  • 2
    /\w/ allows underscores. Jun 4, 2014 at 15:28
  • 6
    You should use /\A[a-zA-Z0-9]*\z/. If you use only ^...$ it will validate only first line of string, e.g. "asdffs\n$&" =~ /^[a-zA-Z0-9]*$/ will return 0 and condition will pass. With \A...\z it looks "asdffs\n&" =~ /\A[a-zA-Z0-9]*\z/ and returns nil. Therefore don't use ^...$ unless you want to test only first line of string.
    – edariedl
    Jun 4, 2014 at 16:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.