jQuery Simple Validation Plugin
I find that I end up consistently adding form validation to sites, and for some reason, I never made a plugin out of it. I feel like every jQuery validation plugin that I look at is way too bloated for what I really need, so I finally whipped up a simple validation plugin that comes in at about 1.5kb.
I tried to keep it really simple with this plugin: just check to see if a field that has been marked as required is not empty and check to see if an email address is valid.
If you want to skip ahead, Check out the demo and download the plugin from GitHub.
Start with the Markup
To get started, I would always start with a simple form marked up in an ordered list:
Then, I need some way to denote which fields should be validated. The HTML5 required attribute, just isn’t supported well enough to use, so all that is needed is to add the class of required to each field that needs to be validated.
Since I have an email field, I also need to add the class of email to the email field:
I also want to tell my plugin which forms to validate, so I’ll also add a class to the form itself:
It’s JavaScript Time
Get started by including jQuery and my Simple Validate plugin. Then, include them on the page:
Now, I just need to call my plugin on any form that has required fields:
Just like that, the form validation will work, but I want to customize a few of the options. First, I want to change the error element to use an <em> tag instead of a <strong> tag:
Then, maybe I decide that I want to submit the form via AJAX. There is no need to add that kind of functionality into the plugin, AJAX is so easy with jQuery. So I just need to tell the plugin that I’m going to submit the form with AJAX, and then pass in my callback function which will fire once the form is submitted with no errors:
Options
Here are all of the available options for the plugin:
- errorClass: 'error' Class for the error message text
- errorText: '{label} is a required field.' Structure for the error message text, {label} will be replaced with the associated label text
- emailErrorText: 'Please enter a valid {label}' Structure for the email error message text, {label} will be replaced with the associated label text
- errorElement: 'strong' Element to use for the error message text
- removeLabelChar: '*' If there is an extra character in the label to denote a required field, strip it out
- inputErrorClass: '' Class to add to an input when it is marked as having an error
- completeCallback: '' Function to call once the form is error-free
- ajaxRequest: false If you don't want to use the default form action and want to submit it via AJAX
Check out the demo and download the plugin from GitHub. Let me know if you run into any bugs or have any feature requests.