Usage
Specifying Validation Rules
Form validation requires passing in a validation object with the rules required to validate your form.
Passing Parameters to Rules New in 2.2.3
Typically rules that include a parameter are written minLength[2]
with the value being passed in as brackets.
If passing in properties as a string is not ideal, or if you are pulling values from another javascript variable, it might make sense to consider using value
to pass in the rule value.
Customizing Prompts
Form validation includes default error prompts for most cases, however these can be quite generic. To specify custom personalized values for a validation prompt use the prompt
property with a rule.
Prompt also supports custom templating with the following values replaced
{name} | The current text of a field's label, or if no label available its placeholder text |
{identifier} | The identifier used to match the field |
{value} | The current field value |
{ruleValue} | The value passed to a rule, for example minLength[100] would set this value to 100 |
Matching Fields
By default the property name used in the validation object will match against the id
, name
, or data-validate
property of each input to find the corresponding field to match validation rules against.
If you need to specify a different identifier you can use the identifier
property on each validation rule
Validating Programmatically
Updated in 2.2.8
Form validation provides additional behaviors to programmatically trigger validation for either the form or an individual field, and check validation on the form or individual fields.
Please see the behaviors section for an explanation on syntax.
validate form | Validates entire form and displays errors if necessary |
is valid | Returns whether a form is valid |
is valid(fieldName) | Returns whether a field in a form is valid (does not update UI) |
validate field(fieldName) | Validates a particular field and displays errors if necessary |
Rules
Validation Rules
Validation rules are a set of conditions required to validate a field
Empty
empty | A field is empty |
checked | A checkbox field is checked |
Content Type
A field is a valid email address | ||
url | A field is a url | |
integer | A field is an integer value, or matches an integer range | integer or integer[1..10] |
decimal | A field must be a decimal number | |
number | A field is any number decimal or non-decimal | |
regExp[expression] | Matches against a regular expression, when using bracketed notation RegExp values must be escaped. |
regExp[/^[a-z0-9_-]{3,16}$/gi]]
Or
regExp[/^[a-z0-9_-]{3,16}$/]]
|
Payment
creditCard | A field is a valid credit card | creditCard |
creditCard[types] | A field matches a specified array of card types | creditCard[visa,mastercard,unionpay] |
Specified Content
contains | A field contains text (case insensitive) | contains[foo] |
containsExactly | A field contains text (case sensitive) | containsExactly[foo] |
doesntContain | A field doesn't contain text (case insensitive) | doesntContain[foo] |
doesntContainExactly | A field doesn't contain text (case sensitive) | doesntContainExactly[foo] |
is | A field is a value (case insensitive) | is[foo] |
isExactly | A field is a value (case-sensitive) | isExactly[foo] |
not | A field is not a value (case insensitive) | not[foo] |
notExactly | A field is not a value (case sensitive) | notExactly[foo] |
Length
minLength | A field is less than a min length | minLength[5] |
exactLength | A field is exactly length | exactLength[16] |
maxLength | A field is less than a max length | maxLength[50] |
Matching Fields
match | A field should match the value of another validation field, for example to confirm passwords | match[password] |
different | A field should be different than another specified field | different[choice] |
Selection Count
minCount | A multiple select field contains at minimum (count) selections | minCount[count] |
exactCount | A multiple select field contains exactly (count) selections | exactCount[count] |
maxCount | A multiple select field contains at maximum (count) selections | maxCount[count] |
Adding Custom Rules
You can extend form validation to include your own rules. Keep in mind these will need to be executed synchronously.
Built-in Events
Form will automatically attach events to specially labeled form fields
- Fields will blur on
escape
key press - Fields will submit form on
enter
- Submit events will be attached to
click
on any element inside the form with classsubmit
- Reset events will be attached to
click
on any element inside the form with classreset
- Clear events will be attached to
click
on any element inside the form with classclear
Manipulating Forms
Reset / Clear Fields
Calling $('form').form('reset')
, or clicking any reset element will return all form values to their default value. This is the value the form fields were set to when the page loaded.
Calling $('form').form('clear')
will remove all values from form fields and reset dropdowns to placeholder text
Writing Values
Form includes behaviors for reading from and writing to form fields.
Getting Values
You can also read values from form fields using get value
and get values
Rule Examples
Empty
The following shows examples of validating different types of empty or unchecked content.
Content Type
Inputs can match against common content types, or your own custom regular expressions.
Payment
Inputs can validate credit cards and other payment types.
Card Name | Validation Name | Test Card Number |
Visa | visa |
4565340519181845 |
American Express | amex |
378282246310005 |
Mastercard | mastercard |
5200828282828210 |
Discover | discover |
6011111111111117 |
Unionpay | unionpay |
6240008631401148 |
JCB | jcb |
3530111333300000 |
Diner's Club | dinersClub |
38520000023237 |
Maestro | maestro |
6799990100000000019 |
Laser | laser |
630490017740292441 |
Visa Electron | visaElectron |
4917300800000000 |
Matching Fields
Fields can be required to match, or not match other fields. You may consider using this with optional fields.
Length
Inputs can match against length of content
Specified Content
Validation rules can specify content that should or should not appear inside an input
Selection Count
Multiple selects can specify how many options should be allowed.
Form Examples
Adding Rules Programmatically New in 2.2.11
You can use the special behaviors add field/rule
, remove rule
and remove field
to dynamically add or remove fields or rules.
Validating Dropdowns
Dropdowns can also be validated like other form fields. Simply match the validation rule to the input
or select
associated with the dropdown
Using Server Name Attributes
Sometimes an integration requires you to use a specific value for name
, or id
. In these cases, you can match a form field using the data-validate
property.
Dependent Fields
New in 2.2
You can specify validation fields to only be used when other fields are present. Simply add depends: 'id'
with the ID of the field that must be non-blank for this rule to evaluate.
Optional Fields
Adding the parameter optional: true
will only add your validation rules when the field is not empty.
Setting Site Defaults
You can specify site wide validation settings by modifying $.fn.form.settings.defaults
that will apply on any form validation if the field appears in the form.
Displaying Error Messages
Forms that contain a ui message error block will automatically be filled in with form validation information.
Validating on Blur and other Events
Validation messages can also appear inline. UI Forms automatically format labels with the class name prompt
. These validation prompts are also set to appear on input change instead of form submission.
Creating Custom Validation
You can use multiple arbitrary rules to validate a form
Behaviors
All the following behaviors can be called using the syntaxsubmit | Submits selected form |
is valid | Returns true/false whether a form passes its validation rules |
add rule(field, rules) New in 2.2.11 |
Adds rule to existing rules for field, also aliased as add field |
add fields(fields) New in 2.2.11 |
Adds fields object to existing fields |
remove rule(field, rules) New in 2.2.11 |
Removes specific rule from field leaving other rules |
remove field(field) New in 2.2.11 |
Remove all validation for a field |
add prompt(identifier, errors) | Adds error prompt to the field with the given identifier |
is valid(fieldName) | Returns true/false whether a field passes its validation rules |
validate form | Validates form, updates UI, and calls onSuccess or onFailure |
validate field(fieldName) | Validates field, updates UI, and calls onSuccess or onFailure |
get field(id) | Returns element with matching name, id, or data-validate metadata to ID |
get value(id) | Returns value of element with id |
get values(ids) | Returns object of element values that match array of ids. If no IDS are passed will return all fields |
set value(id) | Sets value of element with id |
set values(values) | Sets key/value pairs from passed values object to matching ids |
get validation(element) | Returns validation rules for a given jQuery-referenced input field |
has field(identifier) | Returns whether a field exists |
add errors(errors) | Adds errors to form, given an array errors |
add prompt(id, prompt) | Adds a custom user prompt for a given element with id |
Settings
Form Settings
Form settings modify the form validation behavior
Setting | Default | Description |
---|---|---|
keyboardShortcuts | true | Adds keyboard shortcuts for enter and escape keys to submit form and blur fields respectively |
on | submit | Event used to trigger validation. Can be either submit, blur or change. |
revalidate | true | If set to true will revalidate fields with errors on input change |
delay | true | Delay from last typed letter to validate a field when using on: change or when revalidating a field. |
inline | false | Adds inline error on field validation error |
transition | scale | Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions |
duration | 150 | Animation speed for inline prompt |
Form Prompts
Settings to modify default form prompts
Setting | Default |
---|---|
text |
text: {
unspecifiedRule : 'Please enter a valid value',
unspecifiedField : 'This field'
}
|
prompt |
prompt: {
empty : '{name} must have a value',
checked : '{name} must be checked',
email : '{name} must be a valid e-mail',
url : '{name} must be a valid url',
regExp : '{name} is not formatted correctly',
integer : '{name} must be an integer',
decimal : '{name} must be a decimal number',
number : '{name} must be set to a number',
is : '{name} must be \'{ruleValue}\'',
isExactly : '{name} must be exactly \'{ruleValue}\'',
not : '{name} cannot be set to \'{ruleValue}\'',
notExactly : '{name} cannot be set to exactly \'{ruleValue}\'',
contain : '{name} cannot contain \'{ruleValue}\'',
containExactly : '{name} cannot contain exactly \'{ruleValue}\'',
doesntContain : '{name} must contain \'{ruleValue}\'',
doesntContainExactly : '{name} must contain exactly \'{ruleValue}\'',
minLength : '{name} must be at least {ruleValue} characters',
length : '{name} must be at least {ruleValue} characters',
exactLength : '{name} must be exactly {ruleValue} characters',
maxLength : '{name} cannot be longer than {ruleValue} characters',
match : '{name} must match {ruleValue} field',
different : '{name} must have a different value than {ruleValue} field',
creditCard : '{name} must be a valid credit card number',
minCount : '{name} must have at least {ruleValue} choices',
exactCount : '{name} must have exactly {ruleValue} choices',
maxCount : '{name} must have {ruleValue} or less choices'
}
|
Callbacks
Callbacks specify a function to occur after a specific behavior.
Setting | Context | Description |
---|---|---|
onValid | field | Callback on each valid field |
onInvalid | field | Callback on each invalid field |
onSuccess(event, fields) | form | Callback if a form is all valid |
onFailure(formErrors, fields) | form | Callback if any form field is invalid |
Templates
Templates are used to construct elements
Template | Arguments | Description |
---|---|---|
error | Errors (Array) | Constructs the contents of an error message |
prompt | Errors (Array) | Constructs an element to prompt the user to an invalid field |
DOM Settings
DOM settings specify how this module should interface with the DOM
Setting | Default | Description |
---|---|---|
namespace | form | Event namespace. Makes sure module teardown does not effect other events attached to an element. |
selector |
selector : {
message : '.error.message',
field : 'input, textarea, select',
group : '.field',
input : 'input',
prompt : '.prompt',
submit : '.submit'
}
|
Selectors used to match functionality to DOM |
metadata |
metadata : {
validate: 'validate'
},
|
HTML5 metadata attributes |
className |
className : {
active : 'active',
placeholder : 'default',
disabled : 'disabled',
visible : 'visible'
}
|
Class names used to attach style to state |
Debug Settings
Debug settings controls debug output to the console
Setting | Default | Description |
---|---|---|
name | Form | Name used in debug logs |
debug | False | Provides standard debug output to console |
performance | True | Provides standard debug output to console |
verbose | False | Provides ancillary debug output to console |
errors |
errors : {
method : 'The method you called is not defined.'
}
|