Usage
Specifying Validation Rules
Form validation requires passing in a validation object with the rules required to validate your form.
Passing Parameters to Rules
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 |
Native Browser Validation
You can also make use of the native browser built-in form validation without the need to specify rules. You can still provide rules in addition, but you could also completely rely on native validation.
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 or matches a decimal range | decimal or decimal[0.1..1.5] |
number | A field is any number decimal or non-decimal or matches a number range | number or number[1..10] |
minValue | A field has a minimum number decimal or non-decimal | minValue[1.5] |
maxValue | A field has a maximum number decimal or non-decimal | maxValue[50] |
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] |
size | A field has a size between min and max characters | size[6..12] |
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
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
You can specify validation fields to only be used when other fields are present. Simply add depends: 'identifier'
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
Handling dates from calendars
Calendar fields are automatically validated, but you might want to grab the value as a Date object, or as its input, or maybe format it to exactly fit your needs.
Dirty / Clean state
When initialized, form has a clean state that record all field values. Once at least one field is modified, form enter in dirty state, that can be caught through the onDirty
event.
Dirty fields can be retrieved by calling the $('form').form('get dirty fields')
method, and form can be set to a clean state even with new values by calling the $('form').form('set as clean')
method. All new values will then be set as default.
It is also possible to prevent leaving the page when the form has a dirty state, by setting the preventLeaving
parameter to true.
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) | Adds rule to existing rules for field, also aliased as add field |
add fields(fields) | Adds fields object to existing fields |
remove rule(field, rules) | Removes specific rule from field leaving other rules |
remove field(field) | Remove all validation for a field |
is valid(fieldName, showErrors) | Returns true/false whether a field passes its validation rules. If you add true as the second parameter, any failed rule will update the UI |
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(identifier) | Returns element with matching name, id, or data-validate metadata to identifier |
get value(identifier) | Returns value of element with id |
get values([identifiers]) | Returns object of element values that match array of string identifiers. If no IDs are passed will return all fields |
set value(identifier, value) | Sets value of element with id |
set values(values) | Sets key/value pairs from passed values object to matching identifiers |
get validation(element) | Returns validation rules for a given jQuery-referenced input field |
has field(identifier) | Returns whether a field exists |
add errors(error) add errors([errors]) add errors({identifier:error}) add errors({identifier:[errors]}) |
Manually add errors to form, given an array of string errors or an object using keys as field identifier each containing an error string/array of strings value. Such object will automatically add the field label infront of the error message or, if inline:true , will display the inline prompt to the related field. |
remove errors | Removes all current errors from the error message box |
add prompt(identifier, error) add prompt(identifier, [errors]) |
Adds a custom user prompt for a given element with identifier displaying a given string or an array of strings as a bulleted list |
clear | Empty all fields and remove possible errors |
reset | Set all fields to their initial value and remove possible errors |
set defaults | Set fields actual values as default values |
get dirty fields | Return elements which have been modified since form state was changed to dirty |
set as clean | Set the state of the form to clean and set new values as default |
set auto check | Automatically adds the "empty" rule or automatically checks a checkbox for all fields with classname or attribute required |
set optional(identifier, bool = true) | Set or unset matching fields as optional |
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 |
shouldTrim | true | Whether or not the form should trim the value before validating |
dateHandling | date | Define how calendar values will be returned. Can be either date, input or formatter. |
transition | scale | Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions |
duration | 200 | Animation speed for inline prompt |
preventLeaving | false | Prevent user from leaving the page if the form has a dirty state by displaying a prompt |
autoCheckRequired | false | Whether fields with classname or attribute required should automatically add the "empty" rule or automatically checks checkbox fields |
errorFocus | true | Whether, on an invalid form validation, it should automatically focus either the first error field (true ) or a specific dom node (Use a unique selector string such as .ui.error.message or #myelement ) or nothing (false ) |
errorLimit | 0 | Number of max shown errors per field if a field got multiple rules (0=unlimited). This can also be provided for each field individually inside the fields setting. See the Full Validation Settings Example |
Form Prompts
Settings to modify default form prompts
Setting | Default |
---|---|
text |
text: {
unspecifiedRule : 'Please enter a valid value',
unspecifiedField : 'This field',
leavingMessage : 'There are unsaved changes on this page which will be discarded if you continue.'
}
|
prompt |
prompt: {
range : '{name} must be in a range from {min} to {max}',
maxValue : '{name} must have a maximum value of {ruleValue}',
minValue : '{name} must have a minimum value of {ruleValue}',
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',
exactLength : '{name} must be exactly {ruleValue} characters',
maxLength : '{name} cannot be longer than {ruleValue} characters',
size : '{name} must have a length between {min} and {max} 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',
addErrors : '{name}: {error}',
}
|
Formatters
Settings to modify default returned values. Actually exclusively used with calendar fields (through the dateHandling: 'formatter'
setting).
Setting | Default |
---|---|
formatter |
formatter: {
date: function(date) {
return Intl.DateTimeFormat('en-GB').format(date);
},
datetime: function(date) {
return Intl.DateTimeFormat('en-GB', {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).format(date);
},
time: function(date) {
return Intl.DateTimeFormat('en-GB', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).format(date);
},
month: function(date) {
return Intl.DateTimeFormat('en-GB', {
month: '2-digit',
year: 'numeric'
}).format(date);
},
year: function(date) {
return Intl.DateTimeFormat('en-GB', {
year: 'numeric'
}).format(date);
}
}
|
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 |
onDirty | form | Callback if form state is modified to dirty . Triggered when at least on field has been modified |
onClean | form | Callback if form state is modified to clean . Triggered when all fields are set to default values |
Templates
Templates are used to construct elements
Template | Arguments | Description |
---|---|---|
error | Errors (Array) | Constructs the contents of an error message |
prompt | Errors (Array, className) | Constructs an element to prompt the user to an invalid field using the given className for error label styling |
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 : {
checkbox : 'input[type="checkbox"], input[type="radio"]',
clear : '.clear',
field : 'input:not(.search):not([type="reset"]):not([type="button"]):not([type="submit"]), textarea, select',
file : 'input[type="file"]',
group : '.field',
input : 'input',
message : '.error.message',
prompt : '.prompt.label',
radio : 'input[type="radio"]',
reset : '.reset:not([type="reset"])',
submit : '.submit:not([type="submit"])',
uiCheckbox: '.ui.checkbox',
uiDropdown: '.ui.dropdown',
uiCalendar: '.ui.calendar'
}
|
Selectors used to match functionality to DOM |
metadata |
metadata : {
defaultValue : 'default',
validate : 'validate',
isDirty : 'isDirty'
},
|
HTML5 metadata attributes |
className |
className : {
initial: 'initial',
error : 'error',
label : 'ui basic red pointing prompt label',
pressed : 'down',
success : 'success',
required: 'required',
disabled: 'disabled'
}
|
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.',
noRule : 'There is no rule matching the one you specified',
oldSyntax : 'Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.'
noField : 'Field identifier {identifier} not found',
noElement : 'This module requires ui {element}',
noErrorMessage: 'No error message provided',
}
|