RSS 2.0 Feed

Salid – The Simple jQuery Form Validator

About

Salid provides simple form validation with very little overhead. The current BETA is only 211 lines of code unminified, including the license. It handles the usual form validation culprits, including:

  • › 11 built in validation functions.
  • › Validation on form submission.
  • › Validation of individual fields based on user defined event triggers.
  • › Validation based on form element IDs with a fallback on the name.
  • › Ability to define your own error handler callback or use the default.
  • › Ability to define your own validation methods.
  • › Adds an error class to invalid fields.
  • › Supports the metadata plugin for field validation.

Installation

Installation of the Salid plugin is as simple as:

  1. Download the plugin from one of the URLs provided in the downloads section.
  2. Extract the file to your javascript directory.
  3. In your site layout, make sure to first include the jQuery library, version 1.3.2 or greater.
  4. Include your recently downloaded jquery.salid.js file.
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
        <script type="text/javascript" src="/relative/path/to/js/jquery.salid.js"></script>
        <script type="text/javascript">
        $(function() {
            $('form').salidate({
                'formfield' : {
                    callback: 'required',
                    msg: 'The formfield is required.'
                }
            });
        });
        </script>
        

Options

Salid has very few options but just enough to give you a good trafe-off between functionality and customization. Here are the options for a single validation rule:

Option Values
callback Expects a string referencing a validation rule to apply. The validation rule may be either a built-in rule or a custom, user-defined rule. If a callback is not specified, the validation rule will default to required.
msg Expects an error string which will be displayed in the event the validation rule specified in callback fails. If no string is provided, the message will default to This field is required.
callbackParams This option is entirely optional and should only be used if a validation rule requires additional parameters to be passed. Validation rules that require a value to be passed include minlength, maxlength, and match. If you define a custom validation rule, you have the ability to pass as many parameters as necessary using one of [string|array|object]. Just remember that you will need to handle these variables in your function’s second parameter.

Binding Validation Rules

There are two general methods for binding validation rules:

  1. Binding all validation rules for the entire form on form submission.
  2. Binding rules to individual form elements when a specific event fires.

Examples of each binding method are covered on the examples page. It’s worth noting, however, that you are limited to a specific set of bindings on individual elements given the type of form element you are validating:

Form Element Available Event Bindings
input click, blur, focus, keydown, keyup
select change, click, blur, focus, keydown, keyup
textarea click, blur, focus, keydown, keyup

Defining Custom Validation Rules

Salid allows you to define your own validation rules. The only requirements for creating your own validation functions are that they are prefixed with salid_. Here’s an example of a custom validation function:

        function salid_customValidation(field, params) {
		// return boolean [true/false]
		return (typeof field != 'undefined');
        }
        

Customizing Your Error Display

Salid gives you the ability to customize how you display form errors to the end user. You can chose to either use the default error display or you can create your own.

The default error display is a very simplistic lightbox, centered in the viewport. The styling is completely up to you and only requires modifying a couple of CSS rules.

/* the DIV container */
#salid_wrapper { }
/* the anchor link to close the lightbox */
#salid_wrapper #salid_close { }
#salid_wrapper #salid_close:hover { }
/* the content block containing the unordered list of errors */
#salid_wrapper .salid_content { }
/* unordered list of errors */
#salid_wrapper ul { }
#salid_wrapper ul li { }
        

If you decide you want to use your own error handler, all you need to do is create a callback function which takes a single parameter (an array) containing all errors. There are no restrictions as to the naming of your callback function.

Metadata Plugin Support

Salid includes support for the metadata plugin, enabling you to write entire validation rules within a form field’s class attribute.

<input type="text" name="username" id="username" class="{ callback: 'required', msg: 'A username is required.' }" />
        

You must still specify the field in your validation rules to ensure Salid knows exactly which fields to validate, however:

var validation = { 'username' : null };
        

Examples

Basic Form Field Validation on Submit

Validation rules are written in object literal notation. The following example demonstrates a set of rules for requiring three form fields and a valid email address. Note that the my_email binding is composed of two separate rules stored in an array. When a form element requires multiple validation rules, you must use the callbacks parameter as opposed to the callback parameter.

Click Here For Demo

        $(document).ready(function() {
        	var validation = {
        		'firstname' : {
        			callback: 'required',
        			msg: 'Your first name is required.'
        		},
        		'lastname' : {
        			callback: 'required',
        			msg: 'Your last name is required.'
        		},
        		'my_email': {
        			callbacks: [
        				{
        					callback: 'required',
        					msg: 'An email address is required.'
        				},
        				{
        					callback: 'email',
        					msg: 'Your email address does not appear to be valid.'
        				}
        			]
        		}
        	};
        	$('#form_example1').salidate(validation);
        });
        

Example of a Custom Validation Rule

This example demonstrates how you can create your own custom validation rule. This example also demonstrates the usage of providing a callback parameter for your validation function. In this case, the callback parameter is an array representing the minimum and maximum length of the field. Requirements for creating your own custom validation rule are:

  1. The callback function must be prefixed with salid_
  2. The callback function must return a boolean value (true for valid, false for invalid)

Click Here For Demo

        /**
         * Validates that a field is between min and max characters
         * where min and max come from the params array.
         */
        function salid_range(field, params) {
        	return (salid_minlength(field, params[0]) && salid_maxlength(field, params[1]));
        }

        $(document).ready(function() {
        	var validation = {
        		'firstname' : {
        			callback: 'range',
        			msg: 'Your first name must be between 3 and 10 characters in length.',
        			callbackParams: [3,10]
        		}
        	};
        	$('#form_example2').salidate(validation);
        });
        

Downloads

Downloads are currently available from the following sources:

Support

If you are having issues with Salid you may post a comment below or ask a question on Stack Overflow with a tag of salid.

Suggestions, bug reports, and feature requests are also welcome.

Bug reports can be handled directly from the jQuery page as well.

Change Log

Salid 0.1.0 Beta

  • Initial release on 1/14/10

2 Responses

  1. [...] Salid – The Simple jQuery Form Validator [...]

Leave a Reply

Allowable tags
a, abbr, b, blockquote, cite, code, em, i, strike, strong, pre lang, line

* comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.