Rails - 为输入字段设置自定义验证消息(前端)

时间:2016-08-18 05:20:29

标签: javascript html ruby-on-rails

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

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

text_field:

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

上述方法适用于无效模式,但是,如果字段为空,它还会显示相同的消息&#39;仅允许数字&#39;

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

任何人请帮忙.. 谢谢你...

4 个答案:

答案 0 :(得分:1)

使用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");     
});

答案 1 :(得分:1)

对于客户端验证,您需要在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]&#34;是输入字段中的名称。

答案 2 :(得分:1)

I am adding my answer - how to use the wonderful jquery.validate library for client side validation.

I am using version 1.13.1

Here it goes..

  1. Download the library and place it in app/assets/javascripts/jqueryValidation/dist folder which includes additional-methods.min.js and jquery.validate.min.js.

  2. Add the library in your asset pipeline so that its available globally.

    //= require jqueryValidation/dist/jquery.validate
    //= require jqueryValidation/dist/additional-methods
    
  3. start using the library on the form in your _form.html.erb.

    <%= form_for(@new,:html=>{:id=>"newForm") do |f |%>
        //input fields with text/number/textarea etc
    <%end%>
    
  4. initialize the script and validate the form input fields.

    $("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
    

Similarly, we have submitHandler: function(form) {},onkeyup: function (element, event) {)

Hope it helps. :)

答案 3 :(得分:0)

我认为在模型类中定义它的最佳方法。例如,如果此输入字段与用户模型相关的对象关联,则在模型中定义以下验证,

task_C

请告诉我这是否适合您。