Rockwell Rice
Rockwell Rice

Reputation: 3002

Trying to validate string only has numbers or letters (and can contain spaces)

I am trying to use a validation on a string but for some reason, special characters keep getting through and I just cannot figure out what I am missing here.

Here is what I currently have in the model

  validates :name, presence: true, uniqueness: true, format: { with: /[a-z0-9A-Z]/ , :message => "is not valid" }

I have also tried

  validates :name, presence: true, uniqueness: true, format: { with: /\A[a-z0-9A-Z]\z/ , :message => "is not valid" }

I need to validate that a string only has letters or numbers in it, and can have a space. So test 03 would be valid, but test *** would not. For some reason that last one keeps getting through even though when I run the regex here https://rubular.com/ it does not match to those characters, which should cause this validation to fail I would think.

Any help would be GREATLY appreciated.

Upvotes: 0

Views: 661

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

r = /
    \A            # match the beginning of the string
    [ \p{Alnum}]  # match a space, digit or Unicode letter in a character class
    +             # repeat one or more times
    \z            # match the end of the string
    /x            # free-spacing regex definition mode

"I am told that 007 prefers zinfandel to rosé".match? r
  #=> true 
"007, I am told, prefers zinfandel to rosé".match? r
  #=> false

Note that the use of (the "\p{} construct") \p{Alnum} (or the comparable POSIX expression [[:alnum:]]) is not only useful for non-English text but also for words with diacritical marks that have made their way into the Enlish language, such as "rosé" (which cannot very well be written "rose"). These expressions are documented in Regexp (search within the file).

Upvotes: 0

jancha
jancha

Reputation: 4967

I'm not using RUBY, however, try this regex syntax - this would require only a-zA-Z0-9 and at least one character:

/\A[a-z0-9A-Z ]+\z/

OR this one, if string can be of a length = 0:

/\A^[a-z0-9A-Z ]*\z/

-- updated to include support for space

Upvotes: 2

Related Questions