Form validation

This article describes how to perform client-side validation on forms. Form validation is carried out in two parts, first the form fields are defined and stored in an object, then the object is bound to a HTML form element.

Basic usage

We will use the following HTML form for our basic usage example:

<?= form_open(array('id'=>'myform')) ?>
	<input name="email" value="" />
	<input name="password" value="" />
	<button type="submit">Submit</button>
<?= form close() ?>

The object for defining form fields is called $.phpr.form(). The basic usage looks like this:

var myValidation = $.phpr.form().defineFields(function() { 
	this.defineField('email', 'Email Address').email('Please enter a valid email!');
	this.defineField('password', 'Password').required('You must enter a password!');

This example defines an email and password field with their validation rules. Now that the fields are defined, you can bind them to the form element using $.phpr.validate(), which can be chained in by simply calling .validate() on the form field definition object, like so:

myValidation.validate('#myform').success(function() {
	alert('The form is valid');

Once the validation is bound to the form, it will not submit unless it passes the validation defined by the form field rules. By chaining the .success() function we can trigger an alert to display when the form is valid.