Form Validation Documentation View Live Demo

Dependecies

  • https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
  • https://code.jquery.com/jquery-3.2.1.min.js

How form validation work?

Form validation works in simple 2 steps

  • Configuration (Wiring up with HTML)
  • Scripting

Step 1 : Configuration (Wiring up with HTML)

To make a filed required simply add val-type="text" attribute to your html

<input type="text" class="form-control" name="name" val-type="text" placeholder="John">

for different type of form element we have differnt val-types as follows...

Element Type Val-Type
input [type=text,email,date,number]
textarea
val-type="text"
input [type=file] val-type="file"
input [type=radio] val-type="radio"
input [type=checkbox] val-type="check"
select val-type="select"

To display error we need to add a < span class="help-block" >

<div class="form-group"> <label class="control-label">First Name</label> <input type="text" class="form-control" name="first name" val-type="text" placeholder="John"> <span class="help-block"></span> </div>

If the span block is not sibling of the element we want to validate then we need to add an additional attribute with-parent="yes"

<div class="form-group"> <label for="txtAcceptTandC"> <input type="checkbox" id="txtAcceptTandC" name="Term and Condiation" val-type="check" with-parent="yes"> Accept Term and Conditions </label> <span class="help-block"></span> </div>

For Regualr Expression, you simply need to add one more additional attribute regex="email"

<div class="form-group"> <label class="control-label">Email Address</label> <input type="text" class="form-control" name="email address" val-type="text" regex="email" placeholder="sample@domain.com"> <span class="help-block"></span> </div>

and in verifyInput($input, $type){...} you need to specify email regex as shown below

function verifyInput($input, $type) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; switch ($type) { case 'email': return mailformat.test($input); break; default: return false; break; } }

Step 2 : Scripting

Give Id to your form and the submit button

<form class="inline-form" id="sampleForm"> <div class="row">...</div> <div class="row"> <div class="col-sm-12"> <div class="form-group"> <button type="submit" id="btnAdd" class="btn btn-default">Add</button> </div> </div> </div> </form>

Once you are done, you just need to call the formValidator

$('#btnAdd').on('click', function () { if (!formValidator('#sampleForm')) { return false; } });