Skip to content
Michael Gunderson edited this page Jul 17, 2013 · 4 revisions

Pliant - A flexible jQuery validation plugin.

Features

  • Central or field specific rule definitions.
  • Rule inheritance, and overriding.
  • Change rule validation messages dynamically during validation.
  • Validation on field change.
  • Validation chaining for fields and/or rules.
  • Add or remove fields on the fly.
  • Enable or disable fields or rules on the fly.
  • Set fields valid state manually.
  • Define validation using HTML comments (plugin).
  • Control field/rule message locations globally, or on a per field/rule instance.
  • Control what triggers form validation, and what scope.
  • Halt validation on first invalid rule per field, or validate all rules per field.
  • Ignore or include hidden/disabled fields.
  • Customize the element type and style for fields, messages, containers, and wrappers.
  • Allows multiple event handlers to bind to events.
  • Control field validation on change globally, or per field/rule based on a bool or the return of a function.
  • Extensible via plugins.
  • And more...

Options

Option Type Default Value Description
appendRulesToFieldClass bool false Rule names are appended to their fields class. These are in sync, so if you later disable/enable a rule, the class will reflect that.
reconcileFieldOrder bool false Fields will be validated in the order they appear on the form, instead of the order they're added.
haltOnFirstInvalidRule bool true Validation for each field will stop on the first invalid rule. Otherwise, multiple validation errors will show per field.
hideMessageContainerOnLoad bool true Hide the messageContainer on init if possible.
validateOnChange bool true Trigger validation for fields when their content changes, unless overridden by the field/rule.
focusFirstInvalidField bool false
ignoreHidden bool true Fields not visible during validation will be ignored.
ignoreDisabled bool true Fields not enabled during validation will be ignored.
validateOnSubmit bool true Validation will be fired upon submission of the form, or whatever validateOnSubmitSelector is set to.
validateOnSubmitSelector string/selector null Submit validation will only trigger for elements returned by this selector. You can pass in a string selector, or a jQuery object containing results of a selection.
validateOnSubmitEvent string 'click' The event to subscribe to for elements returned by validateOnSubmitSelector.
validateOnSubmitScope string/selector null Selector to use for the scope when binding the validateOnSubmitSelector. If null, the scope from Pliant instantiation is used.
inputSelector string/selector ':input[type!=button]' Selector for fields. Used when reconcileFieldOrder is enabled.
messageElement string '' Default element to wrap around error message text.
messageWrap string null Element to wrap around the messageElement.
messageContainer string/selector null Element to stick all validation messages in. Used for centralized validation, such as at the top of the page.
messageElementClass string 'pl-element-error' CSS class applied to validation message elements.
messageWrapClass string 'pl-wrap-error' CSS class applied to validation message wrappers.
inputClass string 'pl-input-error' CSS class applied to invalid input fields.
plugins Object null Plugins and their options to load.
rules Object see-below An object containing validation rules for fields to use.
fields Array [] An array of fields to apply validation to. They're validated in the order added, unless you us the reconcileFieldOrder option.

Default Rules

By default, the below rules are already available in Pliant. You can override them if needed.

Name Options Default Message Description
required -- 'Required' Validates that a field has a value.
numeric -- 'Numeric only' Validates that a fields value is numerical.
length (int)min, (int)max 'Invalid length' Validates that the fields value is within the length specified by the options.

Rule Object

{
    dateformat: { //This is the name of the rule we're adding.
        message: 'Invalid date format', //This is the validation message to show.
        validate: function(o) { //This is the rules validate function.
            //The first param will be the rule object itself, which allows you to access custom properties you add to the rule object.
            //Return false for invalid, and true for valid.
            return false;
        }
    }
}
Passing options to a validator?

When defining the rules for a field, you have the ability to override the validator function, and message. You can also add anything you want to the rule object, and it'll be available to the validator during validation.

Example: The length rule has min/max properties. If you want to custom them, you simply override them.

{
    field: $('#somefield'),
    rules: {
        length: {
            min: 1,
            max: 15
        }
    }
}
Rule Options
Name Type Required Description
message string/html Yes The message to display to the user when validation fails.
validate function -- The function to execute that returns false if the field is invalid. If no validate function is given, the rule is always valid. While rare, this allows rules to only be shown via their valid property, using toggle.
validateOnChange bool/function -- If false, the rule will be skipped during validation on change. If a function is provided, its returned bool will determine if the rule should be skipped or not.
enabled bool -- Setting to false on init will disable the rule, until it's re-enabled via toggle.
valid bool -- Setting to false will cause the field to marked as invalid on init, and the UI will reflect that.
container jQuery Object -- Forces the rules message to be placed in the selected container DOM.
inherit string -- Makes the rule inherit another rules properties. You can only inherit from rules defined in the "rules: {}" on init.
Rule Functions

Rule functions are accessed from within the validate function of each rule. The first parameter of validate is the rules properties, which include the functions below.

Note: At no point should you try calling the rules validate function during validation of the rule. It might break time and space.

Name Parameters Description
SetMessage string Immediately sets the current rules message content. Note: The message will revert back automatically on the next validation of the rule, unless you set it again via this function.

Field Object

Note: The order of the rules is the order they're validated.

{
    field: $('#somefieldsid'), //The field to validate.
    rules: { //Same as the above rule object, which allows for rule overriding, or custom rules.
        required: {
            message: 'This message will override the built in "required" validation message'
            //Note: You could create a function here called 'validate' to override the built in validation of the required rule.
        },
        oneoffrule: {
            message: 'This rule only applies to this field...',
            validate: function() {
                return true;
            }
        }
    }
}
Field Options
Option Type Required Description
field jQuery Object Yes Field to validate. Note: This can be a DOM element containing multiple fields too, such as a check box list.
container jQuery Object -- Forces all rule messages to be placed in the container, wherever in the DOM it is. Note: Only rules without a container option will have their messages placed here.
enabled bool -- Disables the field until it's re-enabled via the toggle function.
valid bool -- Ignored during init, but when events return this object, you can check this property to determine the validity.
chain jQuery Object/Array/Chain Object -- Any fields or chain objects specified here will have their validation triggered when this field is validated on change.
validateOnChange bool/function -- If false, field validation will be skipped on change. If a function is used, then its return bool will determine if validation will occur on change.
rules Lit Object Yes* A literal object of rule objects to validate the field with. You can just specify the name and an empty definition if you're not overriding the rules properties, or creating one off rules.
Chain Object

The chain option accepts a jQuery object for a field, an array of them, this following chain object, or an array of chain objects.

{
	field: $('#somefield'),
	rules: 'required' //This can also be an array of strings, containing rule names.
}

Events

All events listed here can be subscribed to by assign a handler to them in the options on init, or by using the on function after init. You can have multiple handlers on init if you want, just assign the event an array of handler functions.

Note: Unless otherwise stated below, the 'this' context of the handler will be the instance of Pliant.

Name Params Description
onPreFieldValidate fieldObject Called when a field is about to be validated.
onPostFieldValidate fieldObject Called when a field has been validated.
onFieldValidate fieldObject Called when a field is validated. Note: While the same as onPostFieldValidate, this event only fires if the validateOnChange option is enabled.
onFormValidate fieldObjectArray, valid Called when validation has completed for the entire form.
onMessagePlacement message If you're handling this event, then you're handing the message placement for Pliant. The "this" context is the field being processed.
onInvalidFIeldFocus fieldObject Called when an invalid field is about to be focused due to the focusFirstInvalidField option being enabled.
onFieldAdded fieldObject Called when a field has been added for validation.
onFieldRemoved fieldObject Called when a field has been removed from validation.
onFieldToggle fieldObject Called when a fields enabled state was toggled via the toggle function.
onRuleToggle ruleName, field, ruleObject Called when a rules enabled state was toggled via the toggle function.
onReady -- Called when Pliant is finished loading.

Functions

Name Params Description
on (string) eventName, (function) handler Binds the handler to be fired for the specified event.
validate -- Triggers validation for all fields added to the instance of Pliant.
reset (Optional/jQuery object) field Resets the validation state for the field back to true, and hides all messages. If no field is supplied, all fields will be reset.
clear -- Removes all registered fields for validation.
validateField (jQuery object) field Triggers instant validation for the specified field.
validateRule (string) rule, (mixed) data Manually calls the validate function for a given rule, and passes the data to it as a parameter.
totalFields -- Returns the total amount of fields registered for validation.
fields -- Returns an array of field objects registered for validation.
invalidCount -- Returns the number of currently invalid fields.
add (Array/Field Object) field Adds validation for a field, or an array of fields.
remove (Selector/jQuery object) field Removes validation for the specified field.
toggle (bool) enabled, (Selector/jQuery object) field, (Optional/String) ruleName Toggles validation for a field or rule.
state (State Object) stateObject Sets the invalid state of rules for a field, and updates the UI to reflect them.
destroy -- Resets all validation, removes all fields for validation, and unbinds event listeners. Similar to creating a new instance.
option (String) key, (Optional/Mixed) val Gets or sets an option. If no val is specified, the current value for the key is returned.
State Object

Note: This object is only used with the state function.

{
    field: $('#somefieldsid'), //The field to target.
    rules: {
        required: false //The key is the rule name for the field, and the value is a bool indicating its validity.
    }
}