My favorites | Sign in
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
Library_LiveForm  
Form management & validation
Updated Sep 9, 2011 by felk...@gmail.com

LiveForm

Everything I've learned about forms since becoming a web developer: they are annoying. LiveForm aims to change this by making forms easily accessible and validation-friendly.

The idea behind LiveForm is that a developer only needs to write HTML to achieve a validated, functional form object in Javascript. This object is then added to the live.forms hash object for easy access.

How It Works

The LiveForm class is instantiated when the DOM has loaded, finding any form with the class live-form attached to it. Once a form has been found, LiveForm will loop through all of it's inputs and store all pertinent form information. Any input with a special validation class will be validated when the form is submitted.

Upon validation, each field is either assigned into one of two hash objects: valid_inputs and invalid_inputs. Each of these are used to log inputs and their values once validation has occurred. When the invalid_inputs hash object has 0 entries in it, the form returns valid.

Example

<form id="myform" name="myform" class="live-form" action="/my_form_action.php">

        FirstName: <input type="text" name="firstname" class="valid-empty"/><br/>
        LastName: <input type="text" name="lastname" class="valid-alpha"/><br/>
        Phone: <input type="text" name="phone" class="valid-phone"/><br/>
        Email: <input type="text" name="email" class="valid-email"/><br/><br/>
      	Salary: <input type="text" name="salaray" class="valid-price"/><br/><br/>

        Textarea: <textarea name="body" class="valid-alpha"></textarea><br/><br/>

        Radio: <br />
        <input type="radio" name="sex" value="male" class="valid-bit" /> Male<br />
        <input type="radio" name="sex" value="female" class="valid-bit" /> Female<br /><br />
		
        Checkbox: <br/>
        <input type="checkbox" name="vehicle-bike" value="Bike" class="valid-checkbox" /> I have a bike<br />
        <input type="checkbox" name="vehicle-car" value="Car" class="valid-checkbox" /> I have a car <br/><br/>

        Select: <br/>
        <select name="vehicle-select" class="valid-select">
                <option value="">Choose Something</option>      
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
        </select> <br/><br/>

        <input type="submit" name="myform-submit" value="Sign Up" />

</form>

As you can see from the example above, you have a pretty standard form. The only difference is that this form has specific classes telling LiveForm what type of validation the field requires.

LiveForm Requirements

  • Form element must have an ID attribute
  • Form element must have a name attribute
  • Form element must have the class live-form attached to it
  • All inputs require a name (which you should do anyways)
  • Any input that needs validation needs to have a class of valid-validationName

LiveForm Input Validation Classes

Since live has sweet regular expressions patterns available, LiveForm uses these to validate input values. This is done by adding classes to the input.

Example

class="valid-empty" 
class="valid-alpha"
class="valid-num" 

Above we see that the classes follow this pattern: valid-validationName. The validationName refers to one of live's regexp patterns. Below are all available validation classes:

  • valid-empty - value can't be empty
  • valid-all - value can be anything
  • valid-bit - value must be either 0 or 1
  • valid-decimal - value must be in decimal format
  • valid-alpha - value must be letters only
  • valid-num - value must be numbers only
  • valid-alphanum - value must be alphanumerical
  • valid-email - value must follow email pattern
  • valid-phone - value must follow phone patterns (dashes or no dashes)
  • valid-checkbox - input is a checkbox and must be checked
  • valid-cc - value must follow standard credit card patterns
  • valid-zip - value must follow standard zip code formats
  • valid-price - value must follow US price formats. currency is optional

More Lively Form Fun

Remember how we said that LiveForm runs on DOM Load and is attached to the live.forms hash object? The purpose of this is two fold: 1) you don't have to store variables pointing to the form and 2) you can access your form by just chaining methods. Below is some common functionality of LiveForm.

Access

Retrieves the object from the live.forms hash object. Passing the form element's name attribute as the formName parameter is required.

live.forms.get(formName);

Form Inputs

Returns a nodelist of form inputs

live.forms.get(formName).inputs

Valid Inputs

Hash object logging valid inputs. Updated each time the form is validated.

// shows input name
live.forms.get(formName).valid_inputs.key()

// shows input value
live.forms.get(formName).valid_inputs.values()

Invalid Inputs

Hash object logging invalid inputs.Updated each time the form is validated.

// shows input name
live.forms.get(formName).invalid_inputs.key()

// shows input value
live.forms.get(formName).invalid_inputs.values()

Manually Validate Form

live.forms.get(formName).validate()

Reset Values

Resets all form values

live.forms.get(formName).reset()

Request

Calls the request function on the form, which is a Prototype implementation (read more on this if you're interested). This is really useful if using AJAX to submit the form. It serializes all the values of the form and posts to the URL defined in the form elements's action attribute. More on this below with success call backs.

live.forms.get(formName).request()

Call Me Back!

Most of the time, you'll want the form to do something after validation happens. We've implemented callback functions for success and failed validation. The callback functions expect a function (pre-defined or vanilla) to methodize and then call. If a vanilla function is methodized, the form object is passed back to the function, where all of it properties / methods can be accessed. The form object can be accessed by passing it as the first parameter in the vanilla function. See below.

Note on call backs: To make IE8 happy, these call backs must be assigned on window load and have to wrapped with an Event observation.

Success Call Back

// pre-defined function
live.forms.get(formName).success(my_succes_function);

// vanilla function
live.forms.get(formName).success(function(form) {

   //alerts a congrats message
   alert("Congrats! " + form.container.name + " validated!");

});

Failure Call Back

// pre-defined function
live.forms.get(formName).failure(my_failure_function);

// vanilla function
live.forms.get(formName).failure(function(form) {

     // alert all the names of the inputs the failed to validate 
     alert(form.invalid_inputs.keys());

});

All Together Now

Below is a simple example of a login form with success and failure callbacks along with AJAX submission.

<form id="login-form" name="login-form" class="live-form" action="log_me_in.php">

        Username: <input type="text" name="username" class="valid-empty"/><br/>
        LastName: <input type="text" name="password" class="valid-empty"/><br/>

        <input type="submit" name="myform-submit" value="Login" />

</form>

<script type="text/javascript">
		
Event.on(window,'load',function() {
	
        // on successful validation	
        live.forms.get('login-form').success(function(form) {

                // make the ajax request to log_me_in.php (form action value)
	        form.request({

                        onSuccess:function(response) { 
                
                                if(response.responseText=="logged_in") {

                                        // go to member page
                                        window.location = "/member_page";

                                }

                        }

                });

	});
	
	// on validation failure	
        live.forms.get('myform').failure(function(form) {

                // build error string
                var error = "The following fields failed to validate:\n\n";
                
                // loop through invalid inputs and append name to error string
                form.invalid_inputs.keys().each(function(input) {

                       error += input.name+"<br/>";

                });

                // sorry bro, alert this error
		alert(error);

	});
			
});
			
</script>
Powered by Google Project Hosting