Wednesday, February 1, 2017

Jquery validator with custom messages

In this post I will show how to use jquery validator with custom error messages.
Containing the How to use Jquery Validator

Output:


  

<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form id="myform">
<br/>
 <div class="container">
  <div class="row">
   <div class="col-xs-3"> 
    <input type="text" name="field1" placeholder="Email" class="form-control"/>
   </div>
  </div>
   <br/>
  <div class="row">
   <div class="col-xs-3">
    <input type="text" name="field2" placeholder="Name"  class="form-control"/>
   </div>
  </div>
  <br/>
  <div class="row">
   <div  class="col-xs-3">
    <input type="submit" value="Save" class="btn btn-primary"/>
   </div>
  </div> 
 </div>
</form>

<style>

.error{
 color:red
}

.container {
     padding-right: 15px;
     padding-left: 25px;
     margin-right: auto;
     margin-left: auto;
}

</style>
<script type="text/javascript">
$(document).ready(function () {

    $('#myform').validate({
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        },
  
  <!-- Start Messages -->  
  messages: {
   field2: {
    required: "Please specify your name"
   },
   field1: {
    required: "We need your email address to contact you",
    field1: "Your email address must be in the format of name@domain.com"
   }
  },
  <!-- End Messages -->
  
        submitHandler: function (form) {
            alert('valid form submitted');
            return false;
        }
    });

});
</script>
</html>

No comments:

Post a Comment