Bootstrap Tutorial - Validate Form Glyphicons








The following code shows how to validate Form Glyphicons.

Example

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.1.0.js'></script>
<script type='text/javascript'
  src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<link rel="stylesheet" type="text/css"
  href="http://getbootstrap.com/dist/css/bootstrap.css">
<style type='text/css'>
body {<!--  w ww . ja v  a 2 s.c o m-->
  padding: 20px;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('form').validate({    
    rules: {
        fname: {
            minlength: 3,
            maxlength: 15,
            required: true
        },
        lname: {
            minlength: 3,
            maxlength: 15,
            required: true
        }
    },
    highlight: function(element) {
        var id_attr = "#" + $( element ).attr("id") + "1";
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        $(id_attr).removeClass('glyphicon-ok').addClass('glyphicon-remove');         
    },
    unhighlight: function(element) {
        var id_attr = "#" + $( element ).attr("id") + "1";
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        $(id_attr).removeClass('glyphicon-remove').addClass('glyphicon-ok');         
    },
    errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function(error, element) {
            if(element.length) {
                error.insertAfter(element);
            } else {
            error.insertAfter(element);
            }
        } 
 });
});//]]>  
</script>
</head>
<body>
  <form class="form-horizontal">
    <div class="form-group has-feedback">
      <label for="fname" class="control-label col-md-6">First Name:</label>
      <div class="col-md-6">
        <input type="text" name="fname" id="fname" class="form-control"
          placeholder="Enter first name" /> <span
          class="glyphicon form-control-feedback" id="fname1"></span>
      </div>
    </div>
    <div class="form-group has-feedback">
      <label for="lname" class="control-label col-md-6">Last Name</label>
      <div class="col-md-6">
        <input type="text" name="lname" id="lname" class="form-control"
          placeholder="Enter last name" /> <span
          class="glyphicon form-control-feedback" id="lname1"></span>
      </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</body>
</html>

Click to view the demo