Validate the format of a string of comma separated words with regex

僤鯓⒐⒋嵵緔 提交于 2020-03-14 05:41:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!