Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate so that no special characters are allowed

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?

like image 526
user3646037 Avatar asked Jun 04 '14 15:06

user3646037


1 Answers

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.

like image 56
Lukas_Skywalker Avatar answered Nov 03 '22 00:11

Lukas_Skywalker