尝试验证字符串仅包含数字或字母(并且可以包含空格)

时间:2019-01-12 18:44:08

标签: ruby regex ruby-on-rails-4

我正在尝试对字符串使用验证,但是由于某些原因,特殊字符不断通过,我只是无法弄清这里缺少的内容。

这是我目前在模型中拥有的

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

我也尝试过

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

我需要验证字符串中是否只有字母或数字,并且可以有空格。因此test 03是有效的,但test ***无效。由于某种原因,即使当我在此处https://rubular.com/运行正则表达式时,最后一个仍能通过测试,这与那些字符不匹配,这会使我认为此验证失败。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我没有使用RUBY,但是,请尝试使用此正则表达式语法-这仅需要a-zA-Z0-9和至少一个字符:

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

如果字符串的长度可以为0,则为该值:

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

-已更新,以包括对空间的支持

答案 1 :(得分:0)

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

请注意,使用(“ \p{} construct\p{Alnum}(或类似的POSIX表达式[[:alnum:]])不仅适用于非英语文本,还适用于变音符号进入Enlish语言的标记,例如“rosé”(不能很好地写为“ rose”)。这些表达式记录在Regexp中(在文件内搜索)。