【问题标题】:Rails - Setting custom validation messages for input field(front-end)Rails - 为输入字段设置自定义验证消息(前端)
【发布时间】:2016-08-18 05:20:28
【问题描述】:

我需要为模式不匹配和空字段表单中的文本字段设置自定义消息。

我已在后端完成所有验证,但我还需要在前端执行此操作。

文本字段:

<%= f.text_field :id_number, pattern: "[0-9]*", required: true, oninvalid: "this.setCustomValidity('Only numbers allowed')", oninput: "setCustomValidity('')" %>

上述方法在无效模式下工作正常,但如果字段为空,它也会显示相同的消息'Only numbers allowed'

如何为适用于所有类型浏览器的不同错误设置不同的消息?

任何人请帮助.. 谢谢。。

【问题讨论】:

  • 你可以试试jqueryvalidation.org
  • 您想要客户端验证吗?你可以在 Rails 中使用内置的服务器端验证
  • @Milind。谢谢,它看起来不错,但是没有那个插件有没有办法做到这一点..
  • @AndreyS。我完成了服务器端验证,但是,我不需要每次都重新加载页面进行验证。因此,我还包括了客户端验证。
  • @GokulM,如果您需要自定义验证,没有办法不使用 jquery 插件或自定义每个属性 :message 属性和自定义 css 的 .field_with_errors 类,rails 在失败时添加到每个字段。跨度>

标签: javascript html ruby-on-rails


【解决方案1】:

我正在添加我的答案 - 如何使用精彩的 jquery.validate library 进行客户端验证。

我正在使用版本1.13.1

来了..

  1. 下载库并将其放在app/assets/javascripts/jqueryValidation/dist文件夹中,该文件夹包括additional-methods.min.jsjquery.validate.min.js

  2. 在您的资产管道中添加该库,使其在全球范围内可用。

    //= require jqueryValidation/dist/jquery.validate
    //= require jqueryValidation/dist/additional-methods
    
  3. 开始使用_form.html.erb 中表单上的库。

    <%= form_for(@new,:html=>{:id=>"newForm") do |f |%>
        //input fields with text/number/textarea etc
    <%end%>
    
  4. 初始化脚本并验证表单输入字段。

    $("form#new_form").validate({
            //use this to ignore autocomplete fields present,if any
            ignore: "", 
            //set rules for input elements using name attribute
            rules: {
            "new_form[address]": "required",
            "new_form[tag]": "required",
            "new_form[title]": {
                      required: true,
                      minlength: 3,
                      maxlength: 100
                    }, 
            "new_form[contact_email]": {
                      required: true,
                      email: true,
                      minlength: 5,
                      maxlength: 100                  
                    },
             "new_form_photos[avatar][]": {
                      required: true,
                      extension: "jpeg|jpg|png|gif"
                    },
               //use this to show custom dedicated placeholder message everytime validation fails...just like dynamic alert
              errorPlacement: function(error, element) {
                     $("#show_error").html("<span class='text-danger' >Fields marked with * are required</span>");
    
                 },
                 //use this callback to get which field is currently failing validation and then add more custom logic if needed
                 //for eg: you want to update the color of name label if validation fails.
                 //validator.errorList contains an array of objects, where each object has properties "element" and "message".  element is the actual HTML Input.
                 invalidHandler: function(e,validator) {
                     //use the key value pair to get => id=new_form_title, to identify your input field
                     for (var i=0;i<validator.errorList.length;i++){
                            console.log(validator.errorList[i].element.attributes['id'].value);
                       if ( validator.errorList[0].element.attributes['id'].value == "new_form_tag"){
                       //handle tag input field here by adding css/alert/focus etc
                          }
                      }
                   }
          });//validation ends
    

同样,我们有submitHandler: function(form) {},onkeyup: function (element, event) {)

希望对您有所帮助。 :)

【讨论】:

    【解决方案2】:

    为您提供一个非常简单的使用 Jquery 进行客户端验证的示例。试试看:

    你的表格,app/views/users/_form.html.erb

    <%= form_for(@message=Message.new, :html => {:id => 'contact-form'}) do |f| %>
    
    <div class="form-group">
      <label for="phoneNo">Phone Number:</label>
        <div class="input-group">
          <span class="input-group-addon" id="basic-addon1">
            <span class="glyphicon glyphicon-phone">  </span>
          </span>
        <%= f.text_field :contact, class: 'form-control' %>
       </div>                           
    </div>
    

    在js文件中:app/assets/javascritps/users.js

    $(document).on('ready page:load', function(){
      $('#contact-form').validate({
        rules:{         
            "message[contact]": { 
                required: true,
                regex: /^[0-9]{10}$/
            }
        },
        messages:{           
            "message[contact]":{
                required: "Enter your contact number",
                regex: "Enter valid contact number"
            }
        },      
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');        
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if(element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        }
      });
    
      $.validator.addMethod("regex", function(value, element, regexpr) {          
        return regexpr.test(value);
      }, "Enter valid number");     
    });
    

    【讨论】:

      【解决方案3】:

      对于客户端验证,您需要在 js 文件中要求 jquery.validate.min(从 https://jqueryvalidation.org/ 获取)。然后您可以使用表单 id 进行验证。假设您的表单 ID 是 #sliderForm 并且您想要验证文本字段

      <input id="slider_banner_title" name="slider_banner[title]" placeholder="Enter title" size="30" title="title" type="text" maxlength="255">
      

      然后这样做:

      $('#sliderForm').validate
        rules:
          "slider_banner[title]":
             required: true
             maxlength: 44
        messages:
          "slider_banner[title]":
             required: "Title can't be blank"
             maxlength: "Maximum 44 characters are allowed"
      

      这里 slider_banner[title]" 是输入字段中的名称。

      【讨论】:

        【解决方案4】:

        我认为在模型类中定义它的最佳方式。例如,如果此输入字段关联到与 User 模型相关的对象,那么您可以在模型中定义以下验证,

        validates :id_number, presence: {message: 'Id number required'}
        validates :id_number, numericality: {message: 'Id number invalid data'}
        

        让我知道这是否适合你。

        【讨论】:

        • 我已经完成了所有的后端验证,这里我只需要前端验证消息..
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 1970-01-01
        • 2014-06-16
        • 2013-10-02
        • 2011-10-21
        • 1970-01-01
        相关资源
        最近更新 更多