UI.Form - Form validation framework

Synopsis

<form class="uiform">
    <!-- Simple items -->
    <input type="text" name="name" id="name"
           ui:label="First Name" ui:validators="[alphaspaces, required]">
    <input type="text" name="email" id="email"
           ui:label="e-Mail" ui:validators="[email, required]">
    <!-- Composite items -->
    <span ui:label="Phone Number">
        (<input type="text" name="areacode" id="areacode""
                ui:validators="[numeric]">) -
        <input type="text" name="phonenum" id="phonenum"
                ui:validators="[numeric, required]">
    </span>
</form>

Description

UI.Form is an advanced validation framework for html forms. It takes care of validation of typical data types, such as numbers, emails, and provides a simple way to plug more special validations on individuals inputs or entire forms.

As a bonus, UI.Form can take care of the form layout, avoiding the tedious with labels and tables.

Dependencies

Overview

Form layout

By default, UI.Form will alter the layout of the form children, putting them in a table with two columns: one for the labels, one for the inputs. The labels are right aligned.

If you want to take control over form layout, add ui:keeplayout="true" to the form:

<form ui:keeplayout="true">
<!-- ... -->
</form>

Form validation

The ui:validators attribute, may specify form-level or input-level validators, depending on where are located (<form> or <input>, <select>, <textarea>). The content of ui:validators attribute must be a javascript expression that evaluates to a array of functions. Each function is a 'validator'.

Input level validators are pretty simple: they receive the input element as parameter, and returns an error message if the input is invalid or UI.Form.VALIDATION_PASSED if everything is ok.

Form level validators are somewhat different: they receive the form element as parameter, and returns UI.Form.VALIDATION_PASSED when no error is detected, but when a validation error happens, the validator returns an array of :mochiref:UI.Form.Error object. Each Error object has a message and a list of erroneous fields associated with that message. Example:

function validateForm(form) {
    if (form['foo'].match(/^\s*$/) && form['bar'].match(/^\s*$/)) {
        return [new UI.Form.Error("Either foo or bar must be specified",
                                  [form['foo'], form['bar']])];
    }
    return UI.Form.VALIDATION_PASSED;
}

UI4W provides some default validators, present in the UI.Form.Validators namespace, thought they can be specified without the UI.Form.Validators prefix.

Validators are called automatically when the form is submitted in the standard synchronous way (cancelling the submit if one or more validators raise errors), or when invoking the UI.Form.prototype.submitAsync() method.

Alternatively, you can call them manually invoking the UI.Form.prototype.validate() method.

Behind of the scenes

UI.Form contains a array of UI.FormItem.

A FormItem represents a 'row' in the form. Each FormItem contains a array of UI.FormInput.

UI.FormInput wraps a <input> element. There is some specializations of UI.FormInput, that handles the other form element (SelectFormInput for <select>, TODO: TextAreaFormImput for <textarea>), but from the UI.Form point of view, they are just FormInputs.

API Reference

Class UI.Form

UI.Form is the facade to the form layout and validation framework.

Inherits from UI.Widget.

UI.Form(element, items=[], validators=[])

Creates a Form, wrapping the element DOM form element. items and validators are the initial values for the UI.Form.prototype.items and UI.Form.prototype.validators properties.

Properties

UI.Form.prototype.element:

The form element wrapped by the form. Read-only

UI.Form.prototype.items:

Array of the UI.FormItem objects. Each items may contain one or more UI.FormInput objects.

UI.Form.prototype.validators:

Array of validators functions. See Form validation.

Signals

submitted:

Fired when the user submits the form. At this stage the form is not validated.

sent:

Fired when the form has been sent and the current page is currently running. This only happens when the form is asyncronous submitted.

validationPassed, validationFailed:

One of these signals are fired after the validation, depending of the validation result.

Static Vars

UI.Form.VALIDATION_PASSED:

Value returned by input and form level validators when the validation passed.

UI.Form.Messages:

Validation messages for the default validators (See Predefined Form Validators).

It contains string objects, named REQUIRED, NOT_VALID, NUMBER, ALPHA, ALPHANUM, ALPHASPACES, ALPHANUMSPACES and EMAIL. You can modify this objects to get custom messages. (Note: If you just want to translate messages, look at UI.Lang).

Example:

UI.Form.Messages.REQUIRED = 'Please, fill this field';
UI.Form.Messages.NOT_VALID = 'Please enter a valid value for this field';

Methods

UI.Form.prototype.render():

Redraws the form, using automatic layout.

UI.Form.prototype.validate():

Trigger form validation. Erroneous fields will be marked with the uierror css class, and a uitip div will be visible when the mouse is over the invalid element.

Emits the validationPassed or validationFailed signals depending on validation status.

Return true if the validation passed, false if failed.

UI.Form.prototype.submitAsync(url=this.element.action, extraNames=[], extraValues=[], method='GET'):

Submits the form asynchronously, to the url specified, only if form validation passes.

extraNames is an array of extra parameters to append on the request. extraValues are the values of these extra parameters (obviously, extraNames and extraValues must have the same length).

TODO: You can also specify the HTTP method for the request. (By now just 'GET' is supported).

Emits the sent signal when the form is sent.

Return a Mochikit's Deferred object, corresponding to the return value of Mochikit's sendXMLHttpRequest, or null if the validation failed.

UI.Form.prototype.invalidInputs():

Returns an array of erroneous <input> elements as reported by the last validation done.

Class UI.Form.Error

Instances of UI.Form.Error are returned by form-level validators when the validation fails.

UI.Form.Error(message, inputElement1, ...)

Constructs a form valdation error with a message and a list of erroneous input fields.

Properties

UI.Form.Error.prototype.message:

The error message.

UI.Form.Error.prototype.fields:

Array of input elements associated with the validation error.

Class UI.FormItem

Note: Most of the time you don't need to manually construct the FormItems, they are constructed automatically for you when declaring a form with the uiform css class.

UI.FormItem(element, label="", inputs=[], flow='horizontal')

Crates a form item (Somewhat equivalent to a form row), wrapping the html element element.

label, inputs and flow are the initial values for the UI.FormItem.prototype.label, UI.FormItem.prototype.inputs and UI.FormItem.prototype.flow properties.

Properties

UI.FormItem.prototype.element:

The DOM element wrapped by the form item. Read-Only.

UI.FormItem.prototype.label:

The item label.

UI.FormItem.prototype.inputs:

An array of UI.FormInput objects, asociated with the <input> elements contained on the form item element.

UI.FormItem.prototype.flow:

The flow for the rendering of the element childs. It can be 'horizontal' or 'vertical'.

Methods

UI.FormItem.prototype.render()

Renders the item in memory, returing a TR element containg the item with the new layout. (Used by UI.Form.prototype.render())

Class UI.FormInput

Note: Most of the time you don't need to manually construct the FormInputs, as they are constructed automatically for you when declaring a form with the uiform css class.

Inherits from UI.Widget.

UI.FormItem(element, validators):

Creates a FormItem, a thin wrapper around the input element element.

validators is the initial value for the UI.FormInput.validators property.

Properties

UI.FormInput.prototype.element:

The <input> element wrapped by the FormInput. Read-Only.

UI.FormInput.validators:

An array of input-level validators functions. See Form Validation.

UI.FormInput.valid:

True if the element value was valid the last time when validation ran.

Methods

UI.FormInput.prototype.validate():

Validates the element data, marking the element with the uierror css class if the validation failed and poping out a tip when the mouse is over the erroneous input.

UI.FormInput.prototype.markError(message):

Mark the element as erroneous, setting the uierror class and poping out a tip with the speciifed message when the mouse is over the input.

UI.FormInput.prototype.showTip():

Shows the popup error tip.

UI.FormInput.prototype.hideTip():

Hides the popup error tip.

UI.FormInput.prototype.unmarkError():

Removes the error uierror class from the element and disables the error message tip.

Class UI.SelectFormInput

UI.SelectFormInput is a UI.FormInput derived class that manages a <select> element.

Inherits from UI.FormInput.

UI.SelectFormInput(element, validators, model):

Creates a SelectFormInput wrapping the <select> element element.

validators is the initial value for UI.SelectFormInput.prototype.validators property.

model is the UI.ListModel used to populate the select field options.

Properties

UI.SelectFormInput.prototype.element:

The <select> element wrapped by the select form input. Read-Only.

Methods

UI.SelectFormInput.prototype.setModel(listModel):

Sets a new UI.ListModel for the select options

Returns the UI.ListModel assigned to the SelectFormInput.

Renders the options according to the UI.ListModel assigned.

Predefined Form Validators

The UI.Form.Validators namespace contains some common used validators include on UI4W. You don't need to fully qualify this validators when declaring them on html using the ui:validators special attribute.

UI.Form.Validators.required(el):

Returns UI.Form.Messages.REQUIRED if the value of the element el is empty or contains only spaces. Otherwise returns UI.Form.VALIDATION_PASSED.

UI.Form.Validators.regexp(regexp, message=UI.Form.Messages.NOT_VALID) (el):

[Note that this function actually returns a validator function. The produced validator function is described below].

Returns message if the value of the element`el` doesn't match the regular expression regexp. Otherwise returns UI.Form.VALIDATION_PASSED.

Note that regexp is a RegExp object, not a string.

UI.Form.Validators.numeric(el):

Returns UI.Form.Messages.NUMBER if the value of the element el is not a number. Otherwise returns UI.Form.VALIDATION_PASSED. Empty or spaces-only values are allowed.

UI.Form.Validators.alpha(el):

Returns UI.Form.Messages.ALPHA if the value of the element el is not alphabetic. Otherwise returns UI.Form.VALIDATION_PASSED. Empty value is allowed.

UI.Form.Validators.alphaspaces(el):

Returns UI.Form.Messages.ALPHASPACES if the value of the element el is not alphabetic-with-or-without-spaces. Otherwise returns UI.Form.VALIDATION_PASSED. Empty value is allowed.

UI.Form.Validators.alphanum(el):

Returns UI.Form.Messages.ALPHANUM if the value of the element el is not alphanumeric. Otherwise returns UI.Form.VALIDATION_PASSED. Empty value is allowed.

UI.Form.Validators.alphanumspaces(el):

Returns UI.Form.Messages.ALPHANUM if the value of the element el is not alphanumeric-with-or-without-spaces. Otherwise returns UI.Form.VALIDATION_PASSED. Empty value isallowed.

UI.Form.Validators.email(el):

Returns UI.Form.Messages.EMAIL if the value of the element el is not an email adress. Otherwise returns UI.Form.VALIDATION_PASSED. Empty value is allowed.

Automatic widget construction details

As seen on Synopsis example, 90%+ of the time you just need to specify your form in html with special attributes and classes. The objects needed to make the form usable are constructed automatically by UI4W. The following is the details about that html->javascript object conversion

ui:validators attribute

The ui:validators attribute, can be present on <form>, <input> and the other form input related elements. It must contains a valid javascript expression that evaluates to a javascript array of function. These array of functions is mapped to the validators property of UI.Form or UI.FormInput.

The UI.Form.Validators.* functions are exported to the global namespace when the expression evaluation is done.

<input> elements

<input ui:validators="js-expression">

The input element only has one special attribute: ui:validators. For details on these attribute see ui:validators attribute.

<select> elements

<select ui:validators="js-expression" ui:model="js-expression">

The select input has two special attributes: ui:validators and ui:model.

ui:model value must be a javascript expression that evaluates to a UI.ListModel object. See UI.ListModel for info about the list models.

ui:validators is parsed as described on ui:validators attribute.

direct <form> children elements

<tag ui:label="label-text-literal">

Each direct <form> child is mapped to a UI.FormItem. The item label is obtained from the ui:label special attribute value, that is string literal. (No javascript expression here ;-).

There is no problem on putting <input> or other form input tags as a direct <form> child: that's just a FormItem with only one FormInput (the typical case, BTW).

For FormItems with more than one input, group the inputs on an element, as shown on the Phone Number in the Synopsis.

<form> elements

<form class="uiform" ui:validators="javascript-expression"
      ui:keeplayout="true|false">

The form element must be declared with the uiform class to be detected by UI4W as a UI. If the attribute ui:keeplayout is specified and the value is "true", UI.Form will not manage the form layout.

ui:validators is parsed as described on ui:validators attribute.

Authors

Copyright

Copyright 2005-2006 Leonardo Soto M. <leo.soto@gmail.com> and Imagemaker IT <http://www.imagemaker.cl>.

This program is licensed under the CDDL v1.0 license, see http://www.sun.com/cddl/cddl.html.