【问题标题】:rails validation to check length of integer and show message if falserails验证检查整数长度并在错误时显示消息
【发布时间】:2013-08-11 17:40:17
【问题描述】:

我正在处理一个电话号码字段,所以我要求它存在

存在:真实

别名

存在:{message:“要求编号”}

而且我希望它的 长度为 10。所以我做了

存在: {message: "Number is requred"} , 长度: {is: 10}

现在我想要 如果输入的数字不是 10 位,那么应该显示一条消息。我试过这个:

presence: {message: "Number is requred"} , length: {is: 10, message: "Number must be 10 digit long."}

但它不起作用。我应该如何实施?

【问题讨论】:

    标签: ruby-on-rails ruby validation


    【解决方案1】:

    尝试使用正则表达式,如下所示:

    validates_format_of :phone, :with => /[0-9]{9}/ 
    

    是 {9} 您要验证的位数

    【讨论】:

      【解决方案2】:

      成功了

      validates_length_of :number, is: 10,  message: "Number must be 10 digit long"  
      

      【讨论】:

      • 除非我记错了,我认为is只能用于验证字符串的长度,而不是数字。
      【解决方案3】:

      validates_format_of :phone, :with => /[0-9]{10}/ ,:message => "联系人应该是 10 位数字" 这适用于 10 位数字,数字

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2022-06-20
        • 1970-01-01
        • 2016-11-08
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多