【问题标题】:validates_format_of :with => URI::regexp(%w(http https)) issue [duplicate]validates_format_of :with => URI::regexp(%w(http https)) 问题 [重复]
【发布时间】:2013-10-02 16:04:37
【问题描述】:

我的模型 abc.rb 中有两个验证

validates_format_of :url, :with => URI::regexp(%w(http https))
validates_format_of :targetUrl, :with => URI::regexp(%w(http https))

validates_format_of :targetUrl 

没有验证输入。无论我输入什么,它都接受。我在其他我有验证的模型上遇到同样的问题 validates_format_of :website, :with => URI::regexp(%w(http https))。 我无法弄清楚为什么
validates_format_of :targetUrl, :with => URI::regexp(%w(http https))validates_format_of :website, :with => URI::regexp(%w(http https)) 的验证失败。

任何提示都会很有帮助。 谢谢

【问题讨论】:

    标签: regex ruby-on-rails-3


    【解决方案1】:

    您不需要以这种方式指定正则表达式格式。使用类似的东西:

    validates :website, format: { with: /(http|https):\/\/[a-zA-Z0-9\-\#\/\_]+[\.][a-zA-Z0-9\-\.\#\/\_]+/i }
    

    显然使用你喜欢的任何正则表达式!

    【讨论】:

    • 同样的问题。我很好奇为什么相同的验证不适用于其他领域。
    • 与什么相同的问题?这是我在我的一个应用程序中使用的验证,所以它肯定有效......
    • 它没有验证 url。我输入它接受的垃圾。另外,我不是在寻找新的验证。我想知道为什么相同的验证格式适用于一个字段而不适用于其他字段。
    • 确保在同一个地方调用给定字段的所有验证。在您的情况下,多次调用 validates_format_of 只会覆盖其他人。
    • 我已经尝试过了,但没有帮助。在其中一个模型中,此验证“validates_format_of :website, :with => URI::regexp(%w(http https))”根本不起作用。
    猜你喜欢
    • 2021-05-21
    • 2011-09-19
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2016-09-23
    相关资源
    最近更新 更多