2016-08-18 46 views
1

我需要设置为文本字段定制的消息中为图案失配和空字段的形式。导轨 - 设置定制验证消息输入字段(前端)

我已经做了在后台的所有验证,但我还需要为此在前端。

text_field:

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

上述一期工程于无效模式很好,但是,它也显示了同样的信息如果该字段为空“只允许数字。”

我如何设置,在所有类型的浏览器的工作原理不同的错误不同的消息?

请人帮助.. 谢谢你..

+1

你可以试试https://jqueryvalidation.org/ – Milind

+0

你想要客户端验证?您可以在Rails – AndreyS

+0

@Milind中使用内置的服务器端验证。谢谢,它看起来不错,但是,有没有办法做到这一点,没有这个插件.. –

回答

1

我是加入我的答案 - 如何运用之妙jqery.validate library用于客户端验证 我使用的版本1.13.1

她E - 这不用..

  1. 下载库,并将其放置在app/assets/javascripts/jqueryValidation/dist文件夹,其中包括addtional-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%>

  • 初始化脚本和验证形式输入字段。

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

    希望它能帮助。 :)

    0

    我觉得在模型类中定义的最佳方式。举个例子,如果此输入字段关联到相关的用户模型,然后一个对象,你在模型中定义下面的验证,

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

    让我知道这对你的作品。

    +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

    对于客户端验证,你需要需要jquery.validate.min(从https://jqueryvalidation.org/得到它)在你的js文件中。然后你可以使用表单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 [标题]”是在输入字段名