The YUI 3 Form Module — Forms and Validation Made Simple

By YUI TeamDecember 3, 2009

Greg Hinch is Lead Front-end Developer for Wiredrive, a web application for digital asset management and presentation, in Los Angeles. He has been developing with YUI since version 0.11.0 and working in front-end web development for the past 5 years.

Greg's Form module was the first public contribution to the YUI 3 Gallery; he submitted the first version within a few hours of the YUI Team's announcement of the Gallery at YUICONF 2009.

Greg's YUI 3 Gallery Form ModuleThe Form module in the YUI 3 Gallery aims to make working with forms simple, including built-in as well as customizable validation and the ability to set errors from the server. There are predefined field classes for all HTML form input types, and you can extend them to create your own specifically tailored fields. Validation is completely customizable on the field level, and includes a number of built-in methods that you can use for validating email addresses, phone numbers, postal codes, dates, times, and IP addresses. That validation can be done at the time of submission or inline as field values change.

A Form object can be completely generated in script or built directly from markup (supporting a progressive enhancement approach). Here's an example of how simple it is to build a form from script:

var myForm = new Y.Form({
	method : "post",
	action : "/test.php?action=submit",
	inlineValidation : true,
	fields : [
		{name : 'input1', type : 'text', label : 'Email Input: ', validator : 'email'},
		{name : 'input2', type : 'text', label : 'Phone Number Input: ', validator : 'phone'},
		{name : 'choiceinput', type : 'choice', label : 'Radio Choices: ', choices : [
			{label : 'Choice A', value : 'A'},
			{label : 'Choice B', value : 'B'},
			{label : 'Choice C', value : 'C'}
		{type : 'submit', label : 'Submit'},
		{type : 'reset', label : 'Reset'}

This example highlights several of the features of the Form module. The attribute inlineValidate is set to true, which causes fields to validate themselves as soon as their valueChange event fires. Preconfigured validators for email and phone numbers are set on two of the inputs as well, and a special field called a ChoiceField is used for a radio button choice input set.

Please see more examples on Github for building a Form from markup and defining a custom DateField, which attaches a YUI 2 Calendar Widget to an input.

I hope you find the Form module useful in your application development, and welcome any comments or suggestions for the addition of features or bugs to fix. For more information please see the documentation on Github.

Questions about the Form component? Every YUI 3 Gallery module has a dedicated discussion forum; here's the one for the Form module.