2016-08-18 45 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 [標題]」是在輸入字段名