Menu

Form Validation

Usage

Specifying Validation Rules

Form validation requires passing in a validation object with the rules required to validate your form.

A validation object includes a list of form elements, and rules to validate each field against. Fields are matched by either the id, name, or data-validate property (in that order) matching the identifier specified in the settings object. Validation objects must use either shorthand or longhand exclusively.
$('.ui.form') .form({ fields: { name : 'empty', gender : 'empty', username : 'empty', password : ['minLength[6]', 'empty'], skills : ['minCount[2]', 'empty'], terms : 'checked' } }) ;
or
$('.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' } ] } } }) ;

Tell Us About Yourself

Submit

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, }] } } });
Submit

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.

Starting in
2.3.1
you can specify prompts as a function. This may be useful when returning validation for fields that require dynamic validation messages.
You can set default messages for each validation rule type by modifying $fn.form.settings.prompt

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'; } } ] }, } }) ;
Submit

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' } ] } } }) ;
Submit

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

Validation rules are found in $.fn.form.settings.rules, to add new global validation rules, modify $.fn.form.settings.rules to include your function.
To pass parameters to a rule, use bracket notation in your settings object. For example type: 'not[dog]'

Empty

empty A field is empty
checked A checkbox field is checked

Content Type

email 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' } ] } } }) ;

Let's go ahead and get you signed up.

Add 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 class submit
  • Reset events will be attached to click on any element inside the form with class reset
  • Clear events will be attached to click on any element inside the form with class clear
Submit
Reset
Clear

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

Form reset works by caching default values on page load. For this to work correctly any form that uses reset will need to initialize on page load.
Reset and clear will modify all form fields, not just those which have validation rules
Submit
Reset
Clear

Writing Values

Form includes behaviors for reading from and writing to form fields.

$('.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 }) ;
Submit
Clear

Getting Values

You can also read values from form fields using get value and get values

Although get values allows you to use any matching identifier, returned values will always use the corresponding name attribute of the element.
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);
Submit

Rule Examples

Empty

The following shows examples of validating different types of empty or unchecked content.

Submit
$('.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.

Submit
$('.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
Submit
$('.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.

Submit
$('.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

Submit
$('.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

Submit
$('.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.

Submit
$('.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.

Adding Multiple Rules and Complex Rules
You can specify shorthand or full rule objects when adding rules. You can also specifiy fields as an array to modify multiple fields..
// 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']) ; }) ;
Add Additional Validation
Remove Additional Validation
Submit
Clear

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' } }) ;
Submit

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' } ] } } }) ;
Submit

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' } ] } } }) ;

Your tickets are all ready to print. Where would you like to send a receipt?

Submit

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' } ] }, };

Your tickets are all ready to print. Where would you like to send a receipt?

Submit

Displaying Error Messages

Forms that contain a ui message error block will automatically be filled in with form validation information.

The template for error messages can be modified by adjusting settings.template.error

Let's go ahead and get you signed up.

Submit

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.

This example also uses a different validation event. Each element will be validated on input blur instead of the default form submit.
$('.ui.form') .form({ fields : validationRules, inline : true, on : 'blur' }) ;

Let's go ahead and get you signed up.

Submit

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?' } ] } } }) ;

Let's go ahead and get you signed up.

Add Dog

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
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

Templates are found in settings.template, to modify templates across all forms, modify $.fn.form.settings.templates to include your function. They must return HTML.
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.' }

Dimmer Message
Dimmer sub-header