Thursday, 5 December 2013

jQuery Form Validation and Twitter Bootstrap 3

I have been doing some work developing mobile applications for my MSc recently.  To support mobile data capture requirements I have made use of twitter bootstrap and the jquery validation framework.  These two frameworks together provide a great toolset for validating input and building responsive applications.  I have made this process slicker by including the mechanism to show and hide validation errors when the forms are changed.  A sample html form is found below which demonstrates how this works.

<form role="form" class="form-horizontal" id="registrationform" name="registrationform" method="post" action="registersave.php">

<div class="form-group">

<label class="col-sm-2 control-label"  for="username">Username</label>

              <div class="input-group">

                     <span class="input-group-addon">*</span>

                     <input type="text" class="form-control" id="username" name="username" placeholder="Username" required="required">

</div>

              <label class="error label label-danger" for="username"></label>           

       </div>

</form>

And the javascript to support the validation is found below:

$(function() {
 $('#username').focus();
 
 $('#registrationform').validate({
  highlight: function(element) {
   $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
   $(element).closest('.form-group').children('.error').removeClass('hide');
  },
  success: function(element) {
   $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
   $(element).addClass('hide');
  }
 });  
});

This produces the following results when data is entered into the form.

No comments:

Post a Comment