简体   繁体   中英

Rails - Setting custom validation messages for input field(front-end)

I need to set custom messages for text field in a form for pattern mismatch and empty field .

I have done all validation in backend but I also need to do this in front-end.

text_field:

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

The above one works fine on invalid pattern but, it also displays the same message 'Only numbers allowed' if the field is empty.

How can I set different messages for different errors that works in all type of browsers?

Anyone please help.. Thank you..

Giving you a very simple Example using Jquery for client-side validation. Try it:

Your form like, 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>

In js file: 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");     
});

For client side validation you need to require jquery.validate.min(get it from https://jqueryvalidation.org/ ) in your js file. Then You can use form id to validate. Suppose your form id is #sliderForm and you want to validate textfield

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

Then do like this:

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

here slider_banner[title]" is name in input field.

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. :)

I think the best way to define this in the model class. For an example if this input field is associated to an object related to the User model then, you define the following validations in the model,

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

Let me know if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM