问题
I'm trying to validate a string of comma separated words from a text field in a ruby class using regex. The following should be valid:
word
word, word, word
word,word,word
And the following should be invalid:
word word word
I thought this would work
/([a-z]+){1}(,\s*[a-z]+)*/i
On Rubular, it seems to be valid, but when I validate in my class as follows, it accepts what should be invalid strings.
@tag_regex = /([a-z]+){1}(,\s*[a-z]+)*/i
validates :tags,
:allow_blank => true,
:format => { :with => @tag_regex, :message => "Invalid tag format." }
I'm not sure whether my problem lies in the regex or with the method of validation itself. Any help is appreciated.
回答1:
You forgot to use ^(start of the string) and $(end of the string)
So,it should be
/^([a-z]+)(,\s*[a-z]+)*$/i
Without ^,$ it would match anywhere in between the string..With ^,$ you are making it match exactly
来源:https://stackoverflow.com/questions/16134379/validate-the-format-of-a-string-of-comma-separated-words-with-regex