gpt4 book ai didi

ruby-on-rails - Rails 验证 NOT 在正则表达式中

转载 作者:行者123 更新时间:2023-12-05 01:14:29 25 4
gpt4 key购买 nike

我正在尝试创建一个 Rails 3 验证,以确保人们没有使用常见的免费电子邮件地址之一。

我的想法是这样的....

validates_format_of :email, :with => /^((?!gmail).*)$|^((?!yahoo).*)$|^((?!hotmail).*)$/

validates_exclusion_of :email, :in => %w( gmail. GMAIL. hotmail. HOTMAIL. live. LIVE. aol. AOL. ), :message => "You must use your corporate email address."

但两者都不能正常工作。有什么想法吗?

最佳答案

基本上,您已经编写了一个匹配任何内容的正则表达式。让我们分解一下。

/
^( # [ beginning of string
(?!gmail) # followed by anything other than "gmail"
. # followed by any one character
)$ # followed by the end the of string
| # ] OR [
^( # beginning of the string
(?!yahoo) # followed by anything other than "yahoo"
. # followed by any one character
)$ # followed by the end of the string
| # ] OR [
^( # beginning of the string
(?!hotmail) # followed by anything other than "hotmail"
.* # followed by any or no characters
)$ # followed by the end the of string
/ # ]

仔细想想,您会发现唯一不匹配的字符串是以“gmail”、“yahoo”、“hotmail”开头的字符串——全部在同时,这是不可能的。

你真正想要的是这样的:

/
.+@ # one or more characters followed by @
(?! # followed by anything other than...
(gmail|yahoo|hotmail) # [ one of these strings
\. # followed by a literal dot
) # ]
.+ # followed by one or more characters
$ # and the end of the string
/i # case insensitive

把它放在一起,你有:

expr = /.+@(?!(gmail|yahoo|hotmail)\.).+$/i

test_cases = %w[ foo@gmail.com
bar@yahoo.com
BAZ@HOTMAIL.COM
qux@example.com
quux
]

test_cases.map {|addr| expr =~ addr }
# => [nil, nil, nil, 0, nil]
# (nil means no match, 0 means there was a match starting at character 0)

关于ruby-on-rails - Rails 验证 NOT 在正则表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com