Form validation
Usage
Specifying Validation Rules
Form validation requires passing in a validation object with the rules required to validate your form.
$('.ui.form')
.form({
fields: {
name : 'empty',
gender : 'empty',
username : 'empty',
password : ['minLength[6]', 'empty'],
skills : ['minCount[2]', 'empty'],
terms : 'checked'
}
})
;
$('.ui.form')
.form({
fields: {
name: {
identifier: 'name',
rules: [
{
type : 'empty',
prompt : 'Please enter your name'
}
]
},
skills: {
identifier: 'skills',
rules: [
{
type : 'minCount[2]',
prompt : 'Please select at least two skills'
}
]
},
gender: {
identifier: 'gender',
rules: [
{
type : 'empty',
prompt : 'Please select a gender'
}
]
},
username: {
identifier: 'username',
rules: [
{
type : 'empty',
prompt : 'Please enter a username'
}
]
},
password: {
identifier: 'password',
rules: [
{
type : 'empty',
prompt : 'Please enter a password'
},
{
type : 'minLength[6]',
prompt : 'Your password must be at least {ruleValue} characters'
}
]
},
terms: {
identifier: 'terms',
rules: [
{
type : 'checked',
prompt : 'You must agree to the terms and conditions'
}
]
}
}
})
;
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.
$('.ui.form').form({
fields: {
color: {
identifier: 'color',
rules: [{
type: 'regExp',
value: /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/i,
}]
}
}
});
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 |
$('.ui.form')
.form({
fields: {
field1: {
rules: [
{
type : 'empty'
}
]
},
field2: {
rules: [
{
type : 'exactly[dog]',
prompt : '{name} is set to "{value}" that is totally wrong. It should be {ruleValue}'
}
]
},
field3: {
rules: [
{
type : 'exactly[cat]',
prompt : function(value) {
if(value == 'dog') {
return 'I told you to put cat, not dog!';
}
return 'That is not cat';
}
}
]
},
}
})
;
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
$('.ui.form')
.form({
fields: {
name: {
identifier : 'special-name',
rules: [
{
type : 'empty'
}
]
}
}
})
;
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 |
$('.ui.form')
.form({
fields: {
email: 'empty',
name: 'empty'
}
})
;
if( $('.ui.form').form('is valid', 'email')) {
// email is valid
}
if( $('.ui.form').form('is valid')) {
// form is valid (both email and name)
}
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.
// some arbitrary business-logic
window.user = {
name : 'Simon',
adminLevel : 1
};
// custom form validation rule
$.fn.form.settings.rules.adminLevel = function(value, adminLevel) {
return (window.user.adminLevel >= adminLevel)
};
$('.ui.form')
.form({
fields: {
dog: {
identifier: 'dog',
rules: [
{
type: 'adminLevel[2]',
prompt: 'You must be at least a level-2 admin to add a dog'
}
]
}
}
})
;
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.
Run Code$('.writing.example form')
// set one value
.form('set value', 'name', 'Jack')
// set several values
.form('set values', {
name : 'Jack',
gender : 'male',
colors : ['red', 'grey'],
username : 'jlukic',
password : 'youdliketoknow',
terms : true
})
;
Getting Values
You can also read values from form fields using get value
and get values
var
$form = $('.get.example form'),
// get one value
colors = $form.form('get value', 'colors'),
// get list of values
fields = $form.form('get values', ['name', 'colors']),
// get all values
allFields = $form.form('get values')
;
console.log(colors);
console.log(fields);
console.log(allFields);
Rule Examples
Empty
The following shows examples of validating different types of empty or unchecked content.
$('.field.example form')
.form({
on: 'blur',
fields: {
empty: {
identifier : 'empty',
rules: [
{
type : 'empty',
prompt : 'Please enter a value'
}
]
},
dropdown: {
identifier : 'dropdown',
rules: [
{
type : 'empty',
prompt : 'Please select a dropdown value'
}
]
},
checkbox: {
identifier : 'checkbox',
rules: [
{
type : 'checked',
prompt : 'Please check the checkbox'
}
]
}
}
})
;
Content Type
Inputs can match against common content types, or your own custom regular expressions.
$('.type.example form')
.form({
on: 'blur',
fields: {
integer: {
identifier : 'integer',
rules: [
{
type : 'integer[1..100]',
prompt : 'Please enter an integer value'
}
]
},
decimal: {
identifier : 'decimal',
rules: [
{
type : 'decimal',
prompt : 'Please enter a valid decimal'
}
]
},
number: {
identifier : 'number',
rules: [
{
type : 'number',
prompt : 'Please enter a valid number'
}
]
},
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter a valid e-mail'
}
]
},
url: {
identifier : 'url',
rules: [
{
type : 'url',
prompt : 'Please enter a url'
}
]
},
regex: {
identifier : 'regex',
rules: [
{
type : 'regExp[/^[a-z0-9_-]{4,16}$/]',
prompt : 'Please enter a 4-16 letter username'
}
]
}
}
})
;
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 |
$('.payment.example form')
.form({
on: 'blur',
fields: {
card: {
identifier : 'card',
rules: [
{
type : 'creditCard',
prompt : 'Please enter a valid credit card'
}
]
},
exactCard: {
identifier : 'exact-card',
rules: [
{
type : 'creditCard[visa,amex]',
prompt : 'Please enter a visa or amex card'
}
]
}
}
})
;
Matching Fields
Fields can be required to match, or not match other fields. You may consider using this with optional fields.
$('.match.example form')
.form({
on: 'blur',
fields: {
match: {
identifier : 'match2',
rules: [
{
type : 'match[match1]',
prompt : 'Please put the same value in both fields'
}
]
},
different: {
identifier : 'different2',
rules: [
{
type : 'different[different1]',
prompt : 'Please put different values for each field'
}
]
}
}
})
;
Length
Inputs can match against length of content
$('.length.example form')
.form({
on: 'blur',
fields: {
minLength: {
identifier : 'minLength',
rules: [
{
type : 'minLength[100]',
prompt : 'Please enter at least 100 characters'
}
]
},
exactLength: {
identifier : 'exactLength',
rules: [
{
type : 'exactLength[6]',
prompt : 'Please enter exactly 6 characters'
}
]
},
maxLength: {
identifier : 'maxLength',
rules: [
{
type : 'maxLength[100]',
prompt : 'Please enter at most 100 characters'
}
]
},
}
})
;
Specified Content
Validation rules can specify content that should or should not appear inside an input
$('.content.example form')
.form({
on: 'blur',
fields: {
is: {
identifier : 'is',
rules: [
{
type : 'is[dog]',
prompt : 'Please enter exactly "dog"'
}
]
},
isExactly: {
identifier : 'isExactly',
rules: [
{
type : 'isExactly[dog]',
prompt : 'Please enter exactly "dog"'
}
]
},
not: {
identifier : 'not',
rules: [
{
type : 'not[dog]',
prompt : 'Please enter a value, but not "dog"'
}
]
},
notExactly: {
identifier : 'notExactly',
rules: [
{
type : 'notExactly[dog]',
prompt : 'Please enter a value, but not exactly "dog"'
}
]
},
contains: {
identifier : 'contains',
rules: [
{
type : 'contains[dog]',
prompt : 'Please enter a value containing "dog"'
}
]
},
containsExactly: {
identifier : 'containsExactly',
rules: [
{
type : 'containsExactly[dog]',
prompt : 'Please enter a value containing exactly "dog"'
}
]
},
doesntContain: {
identifier : 'doesntContain',
rules: [
{
type : 'doesntContain[dog]',
prompt : 'Please enter a value not containing "dog"'
}
]
},
doesntContainExactly: {
identifier : 'doesntContainExactly',
rules: [
{
type : 'doesntContainExactly[dog]',
prompt : 'Please enter a value not containing exactly "dog"'
}
]
}
}
})
;
Selection Count
Multiple selects can specify how many options should be allowed.
$('.multi.example form')
.form({
on: 'blur',
fields: {
minCount: {
identifier : 'minCount',
rules: [
{
type : 'minCount[2]',
prompt : 'Please select at least 2 values'
}
]
},
maxCount: {
identifier : 'maxCount',
rules: [
{
type : 'maxCount[2]',
prompt : 'Please select a max of 2 values'
}
]
},
exactCount: {
identifier : 'exactCount',
rules: [
{
type : 'exactCount[2]',
prompt : 'Please select 2 values'
}
]
}
}
})
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.
// lets only validate username to start
$('.add.example .ui.form')
.form({
username: ['empty', 'minLength[5]']
})
;
// lets toggle some validation based on button
$('.add.example .ui.positive.button')
.on('click', function() {
$('.add.example .ui.form')
// adding longform
.form('add rule', 'gender', {
rules: [
{
type : 'empty',
prompt : 'Entering your gender is necessary'
}
]
})
// adding shorthand
.form('add rule', 'password', ['empty', 'minLength[5]'])
;
})
;
$('.add.example .ui.negative.button')
.on('click', function() {
$('.add.example .ui.form')
// removing multiple at once
.form('remove fields', ['gender', 'password'])
;
})
;
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
$('.ui.dropdown')
.dropdown()
;
$('.ui.form')
.form({
fields: {
gender: 'empty',
name: 'empty'
}
})
;
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.
$('.ui.form')
.form(
fields: {
name: 'empty'
}
})
;
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.
$('.ui.form')
.form({
fields: {
yearsPracticed: {
identifier : 'yearsPracticed',
depends : 'isDoctor',
rules : [
{
type : 'empty',
prompt : 'Please enter the number of years you have been a doctor'
}
]
}
}
})
;
Optional Fields
Adding the parameter optional: true
will only add your validation rules when the field is not empty.
$('.ui.form')
.form({
fields: {
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter a valid e-mail'
}
]
},
ccEmail: {
identifier : 'cc-email',
optional : true,
rules: [
{
type : 'email',
prompt : 'Please enter a valid second e-mail'
}
]
}
}
})
;
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.
$.fn.form.settings.defaults = {
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter a valid e-mail'
}
]
},
// this form doesn't have a cc email but it will not produce an error
ccEmail: {
identifier : 'cc-email',
optional : true,
rules: [
{
type : 'email',
prompt : 'Please enter a valid second e-mail'
}
]
},
};
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.
$('.ui.form')
.form({
fields : validationRules,
inline : true,
on : 'blur'
})
;
Creating Custom Validation
You can use multiple arbitrary rules to validate a form
$('.ui.form')
.form({
fields: {
dog: {
identifier: 'dog',
rules: [
{
type: 'empty',
prompt: 'You must have a dog to add'
},
{
type: 'contains[fluffy]',
prompt: 'I only want you to add fluffy dogs!'
},
{
type: 'not[mean]',
prompt: 'Why would you add a mean dog to the list?'
}
]
}
}
})
;
Behaviors
All the following behaviors can be called using the syntax$('.foo').form('behavior name', argumentOne, argumentTwo)
submit | 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 |
|
prompt |
|
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 |
|
Selectors used to match functionality to DOM |
metadata |
|
HTML5 metadata attributes |
className |
|
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 |
|