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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With