Validator.

About

This a simple, extensible client-side validation object. It's "simple" because it includes only a small and basic set of valdation functions. However, it's very easily extensible so you may add your own types of validation methods.

Introduction

There are quite a few client-side validators out there. However, while most require a particular accompanying Javascript framework, this one does not. Additionally, rather than a bloaty, full-featured validator, the approach taken herein is to create a basic validator that covers most general use-cases. If it doesn't cover yours, you can easily add your own custom tests.

Demo

Please enter your name
Please enter a valid email
Please enter your phone number and area code
40 characters left Please add a message that is 40 characters or less
Please select your country

Prereqs

none.

Compatibility

  • IE8+
  • Firefox, Webkit, Opera
  • iOS, Android

Code

Check fields in a form


	var validator = new Validator();
	var form = document.querySelector('#demo-form');
	var valid = validator.check(form);
				

Adding a custom rule


	// add a rule called "count" that checks an input's length
	validator.addRule('count', function count(val) {
		return val.length <= 40;
	});
				

API

method arguments description
check element,
function success()
Pass in a field or a DOM element. Checks if field (or fields within the DOM element) are valid according to any data-validate / required attributes on each field.
addRule name,
function validator(value)
Create your own validation rule. Give it a name and the function to be used when validating a field. Use your new rule by placing data-validate="name" on a field to validate. The validation function gets the field value to check against.