试图验证字符串只有数字或字母(并且可以包含空格)

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

我正在尝试对字符串进行验证,但由于某种原因,特殊字符不断通过,我无法弄清楚我在这里遗漏了什么。

这是我目前在模型中的内容

  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" }

我需要验证一个字符串中是否只有字母或数字,并且可以有一个 space。所以 test 03 有效,但 test *** 无效。出于某种原因,即使我 运行 这里的正则表达式 https://rubular.com/ 它与那些字符不匹配,但我认为这应该会导致此验证失败。

任何帮助将不胜感激。

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

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

或者这个,如果字符串的长度可以是 0:

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

-- 已更新以包括对 space

的支持
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

请注意,使用 (the "\p{} construct") \p{Alnum}(或类似的 POSIX 表达式 [[:alnum:]])不仅对非英语文本有用但也适用于已经进入英语的带有变音符号的单词,例如 "rosé"(不能很好地写成 "rose")。这些表达式记录在 Regexp 中(在文件中搜索)。