【问题标题】:Trying to validate string only has numbers or letters (and can contain spaces)尝试验证字符串只有数字或字母(并且可以包含空格)
【发布时间】:2019-06-07 08:03:11
【问题描述】:

我正在尝试对字符串使用验证,但由于某种原因,特殊字符不断通过,我无法弄清楚我在这里缺少什么。

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

  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/ 时,最后一个仍然通过,它与那些字符不匹配,我认为这应该会导致此验证失败。

任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

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

    或者这个,如果字符串的长度 = 0:

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

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

    【讨论】:

    • 所以我得到一个失败的验证,我认为是因为一个空格,所以这个失败test 09,但应该通过
    • 谢谢,我将对其进行编辑以使其专门在 ruby​​ 中工作,它抱怨 ^$ 字符。
    【解决方案2】:
    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:]])不仅适用于非英语文本,而且适用于带有变音符号的单词成英语,例如“rosé”(不能很好地写成“rose”)。这些表达式记录在Regexp(在文件中搜索)。

    【讨论】:

    • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
    • @U9-Forward,请解释为什么这个(正则表达式)不能回答问题。
    • @U9-Forward,加油,解释很明显。你想让我说什么,“对于任何字符串str,该字符串是否符合测试的测试是str.match? /\A[\p{Alnum} ]+ ]+/”?然后我应该继续分解琐碎的正则表达式吗?告诉我这个问题的公认答案是否提供了更全面的解释。如果您查看我的其他答案,您会发现我经常提供血淋淋的细节。只是这里不需要。
    猜你喜欢
    • 2013-04-28
    • 2012-09-07
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多