Menu

Form Validation

A form validation behavior checks data against a set of criteria before passing it along to the server

Usage

Validation Definitions

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 against. Fields are matched by either the id tag, name tag, or the data-validate metadata matching the identifier provided in the settings object.
$('.ui.form') .form({ name: { identifier : 'name', rules: [ { type : 'empty', prompt : 'Please enter your name' } ] }, 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 : 'length[6]', prompt : 'Your password must be at least 6 characters' } ] }, terms: { identifier : 'terms', rules: [ { type : 'checked', prompt : 'You must agree to the terms and conditions' } ] } }) ;

Tell Us About Yourself

Submit

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]'
Name Validates Example
checked A checkbox field is checked
contains A field contains text (case insensitive) contains[foo]
containsExactly A field contains exactly text containsExactly[foo]
email A field is a valid email address
empty A field is empty
integer A field is an integer value
is A field matches a value (case insensitive) is[foo]
isExactly A field is exactly text isExactly[foo]
length A field is longer than a length length[6]
match A field matches the value of another validation field match[password]
maxLength A field is less than a max length maxLength[50]
not A field does not match a value (case insensitive) not[foo]
notExactly A field is not exactly text notExactly[foo]
url A field is a url

Keyboard Shortcuts & 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

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

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

Examples

Optional Validation Fields

Adding the parameter optional: true will only add your validation rules when the field is not empty.

$('.ui.form') .form({ 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

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

Behavior

All the following behaviors can be called using the syntax
$('.foo').form('behavior name', argumentOne, argumentTwo)
submit Submits selected form
validate form Validates form and calls onSuccess or onFailure
get change event gets browser property change event
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 field
has field(identifier) Returns whether a field exists
add errors(errors) Adds errors to form, given an array errors

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

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 form Callback if a form is all valid
onFailure 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 True Provides standard debug output to console
performance True Provides standard debug output to console
verbose True Provides ancillary debug output to console
errors
errors : { method : 'The method you called is not defined.' }

Dimmer Message
Dimmer sub-header