BLACKBELT

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.

[js]
<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>
[/js]

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:
[sourcecode language=”css” light=”true”]
function salid_customValidation(field, params) {
// return boolean [true/false]
return (typeof field != ‘undefined’);
}
[/sourcecode]

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.
[sourcecode language=”css” light=”true”]
/* 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 { }
[/sourcecode]

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.

[sourcecode language=”text” light=”true”]
<input type="text" name="username" id="username" class="{ callback: ‘required’, msg: ‘A username is required.’ }" />
[/sourcecode]

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

[sourcecode language=”text” light=”true”]
var validation = { ‘username’ : null };
[/sourcecode]

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
[sourcecode language=”javascript” light=”true”]
$(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);
});
[/sourcecode]

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
[sourcecode language=”javascript” light=”true”]
/**
* 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);
});
[/sourcecode]

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
  • http://ajax.wespai.com wespai

    nice plugin

  • Pingback: BEST AJAX EXAMPLES - Nagpur()

  • hawking

    I found a bug.
    if there are more than 2 validate functions,it would show all error msg when it run error data
    eg.
    var qq_rule = {
    callbacks: [
    {callback: ‘numeric’,msg: ‘qq should be num’},
    {callback: ‘range’,msg: “qq’length should be between 3 and 20”,callbackParams: [3,20]}
    ]
    };

    $(‘#personal_info’).find(‘input[name=qq]’).salid(‘blur’,qq_rule);

    when i input some chars,the error msg “qq should be num qq’length should be between 3 and 20“,that is not my result.maybe it will be overed when it be validated by salid_numeric.

    so,i try it.modifed a line code in function validate.like this
    if (valid && !_validate(field, rule, $form)) valid = false;
    // if (!_validate(field, rule, $form)) valid = false;

    • hawking

      oh.maybe is good handle all validations one times when use function salidate .

  • beng

    nice. thanks for this. :) i have a question though.. how did you make your form below into rounded sides instead of the usual square? i like the style.

  • http://www.smurfworks.com/ Glyn Simpso

    Thank you for this amazing plugin!

    Just a slight bug with IE6/7 – although I can’t confirm if this is just because I’m using IETester, but it seems that console.log (the firebug logging system) is considered non-existent by IE6/7 and returns a script error. I’ve just used a replace-all method in notepad++ of “console.log” to “alert”.

    Seems to work well. Can’t way to see this progress!

  • http://tekhedd.com/ tekHedd

    Can’t seem to find the bug submission form at jquery.com, and this is really more of an enhancement request with patch. I am using salid without a FORM div, in a simplemodal modal dialog. (I’m starting to hate that “one big form” feature of ASP.NET!)

    I’ve modified salid to call the error callback even if there are 0 errors, allowing it to maintain a list of errors that aren’t inline with the failed objects. This seems useful and does not seem to break the builtin functionality. There is, admittedly, some performance overhead, but I couldn’t figure out another clean way to clear the error message log.

    diff -r e9fb0345a5a1 derby.DCServer/admin_app/script/jquery.salid.src.js
    --- a/derby.DCServer/admin_app/script/jquery.salid.src.js Wed May 25 14:08:07 2011 -0600
    +++ b/derby.DCServer/admin_app/script/jquery.salid.src.js Wed May 25 14:46:57 2011 -0600
    @@ -41,7 +41,7 @@
    $.each(elemsToValidate, function(field, params) {
    validate(field, params, $form);
    });
    - return (hasErrors) ? handleErrors(errorCallback, $form) : true;
    + return handleErrors(errorCallback, $form);
    });
    }

    @@ -71,9 +71,8 @@
    this.each(function() {
    var $this = $(this);
    $this.bind(event, function() {
    - if (!validate($this, params)) {
    - handleErrors(errorCallback, $this);
    - }
    + validate($this, params);
    + handleErrors(errorCallback, $this);
    });
    });
    }

    Not sure whether you’ll find this useful, but here it is.

  • http://tekhedd.com/ tekHedd

    Can’t seem to find the bug submission form at jquery.com, and this is really more of an enhancement request with patch. I am using salid without a FORM div, in a simplemodal modal dialog. (I’m starting to hate that “one big form” feature of ASP.NET!)

    I’ve modified salid to call the error callback even if there are 0 errors, allowing it to maintain a list of errors that aren’t inline with the failed objects. This seems useful and does not seem to break the builtin functionality. There is, admittedly, some performance overhead, but I couldn’t figure out another clean way to clear the error message log.

    diff -r e9fb0345a5a1 derby.DCServer/admin_app/script/jquery.salid.src.js
    — a/derby.DCServer/admin_app/script/jquery.salid.src.js Wed May 25 14:08:07 2011 -0600
    +++ b/derby.DCServer/admin_app/script/jquery.salid.src.js Wed May 25 14:46:57 2011 -0600
    @@ -41,7 +41,7 @@
    $.each(elemsToValidate, function(field, params) {
    validate(field, params, $form);
    });
    – return (hasErrors) ? handleErrors(errorCallback, $form) : true;
    + return handleErrors(errorCallback, $form);
    });
    }

    @@ -71,9 +71,8 @@
    this.each(function() {
    var $this = $(this);
    $this.bind(event, function() {
    – if (!validate($this, params)) {
    – handleErrors(errorCallback, $this);
    – }
    + validate($this, params);
    + handleErrors(errorCallback, $this);
    });
    });
    }

    Not sure whether you’ll find this useful, but here it is.

    (OK, how exactly is this a DUPLICATE comment? Hah.)