John Lindal![]()
HTML forms are complex beasts, requiring insertion of default values when the form is first displayed, possible auto-saving of unvalidated input to protect against connection loss, client-side pre-validation of user input, synchronous/asynchronous submission of user input to the server, and processing and display of the results returned by the server (success or errors). When combined with YUI3 IO, FormMgr supports all of this.
This module is lightweight because it does not instantiate a separate JavaScript object for each form element. Instead, basic pre-validation configuration is stored in each element's class. Custom pre-validations can be added either by registering a regular expression and/or function for a particular element or by overriding postValidateForm().
This approach is ideal when implementing progressive enhancement: the form is defined via markup, and FormManager is then used to add functionality when JavaScript is enabled. Even then error message containers are in the markup, and this allows the server to populate them for non-JavaScript clients.
We refer to client-side checks as "pre-validation" because JavaScript is relatively easy to subvert -- or it might be turned off completely by the user. Only the server can truly validate that the data is acceptable.
More information is provided in the YUI Blog post: http://www.yuiblog.com/blog/2010/03/23/gallery-form-manager/
Example of creating a FormManager and adding custom validations. Basic validations like required, min/max length, integer, and decimal are encoded in the markup.
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>YUI({
//Last Gallery Build of this module
gallery: 'gallery-2013.04.03-19-53'
}).use('gallery-formmgr', function(Y)
{
var f = new Y.FormManager('test_form',
{
status_node: '#form-status',
default_value_map: // overrides values in markup
{
s1: 'abc',
b1: 1,
b2: 0
}
});
f.prepareForm();
f.initFocus(); // only do this for one form on a page
// validations
f.setErrorMessages('email',
{
required: 'Please tell us how to spam you. (Just kidding!)',
regex: 'Please enter a valid email address.'
});
f.setRegex('email', /@.+\..+/); // not trying very hard
f.setErrorMessages('zip',
{
regex: 'Please enter a valid US ZIP Code.'
});
f.setRegex('zip', /^[0-9]{5}(?:-[0-9]{4})?$/);
f.setFunction('pw', function(form)
{
if (form.pw.value != form.pw2.value)
{
f.displayMessage(form.pw, 'Your password entries did not match.', 'error');
f.displayMessage(form.pw2, '', 'error');
return false;
}
return true;
});
f.postValidateForm = function(form)
{
var count = 0;
Y.each([form.b1, form.b2, form.b3], function(b)
{
if (b.checked) count++;
});
if (count < 2)
{
f.displayMessage(form.b1, 'Please select at least two checkboxes.', 'warn');
return false;
}
return true;
};
});
© 2006-2013 Yahoo! Inc. All rights reserved.
All code on this site is licensed under the BSD License unless stated otherwise.
About This Site · Security Contact Info