Recipe 11.14 Validating Form Input

11.14.1 Problem

You want to validate user input before allowing a form to be submitted for processing.

11.14.2 Solution

Write a custom validate( ) method for the Form class that checks each form element.

11.14.3 Discussion

ActionScript does not provide a native means by which to validate form input. However, you can add a small amount of code to the custom Form class, with which you can then quickly add validation code to any form. You should add two methods to the custom Form class and add one line of code to the existing constructor.

One method, setValidator( ), should be used to set the validators for any elements requiring validation. The method should take two parameters: the name of the form element as a string and the validator.

The validator can have one of three types of values:

true

If the Boolean true is specified, the element must contain a value. Use this for mandatory form elements.

"email"

If the string "email" is specified, the element's value must be in the format of a valid email address.

Regular expression

If a regular expression is specified, it defines the pattern that the element value must match.

The setValidator( ) method adds new elements to an associative array in which the key is the element name and the value is the validator. You should, therefore, initialize the associative array in the constructor method.

The validate( ) method performs the validation based on the validators that have been specified using setValidator( ). The validate( ) method should loop through the elements of the form and, if a validator has been assigned for the element, verify that the element value meets the criteria. The validate( ) method returns the name of the first element that fails the validation test. Otherwise, the method returns true, indicating that the form validated successfully. The following is a partial listing of our enhanced Form class, which should be stored in a Form.as file. Everything in this listing should be added to the existing contents of Form.as, with one exception. The constructor method shown here should replace the existing constructor code.

// Make sure to include RegExp.as (see Recipe 9.6) in the Form.as file. The // validation methods require it. #include "RegExp.as" _global.Form = function (  ) {   this.formElements = new Array(  );   // Our updated constructor creates the validators associative array.   this.validators = new Object(  ); }; // The setValidator(  ) method adds elements to the validators associative array. Form.prototype.setValidator = function (elementName, validator) {   this.validators[elementName] = validator; }; // The validate(  ) method attempts to validate the form. Form.prototype.validate = function (  ) {   // Retrieve the form's values using getValues(  ).   var values = this.getValues(  );   var valid, re;   // Loop through all the values.   for (var item in values) {     // Get the validator for the current form element.     valid = this.validators[item];     // Validate the element based on its validator (true, "email", or a reg exp).     // Remember that the condition (valid) is the same as (valid == true).     if (valid) {       // If the validator is true, check whether the element has some value.       if ( (values[item] == undefined) || (values[item] == null)            || (values[item] == "")) {         // If no valid value exists, return this item as an error.         return item;       }       } else if (valid == "email") {       // If the validator is "email", make sure it is an email address of the form       // something@somewhere.topleveldomain.       re = new RegExp("^([\\w\-\\.]+)@(([\\w\\-]+\\.)+[\\w\\-]+)$");       if (!re.test(values[item])) {         // If it doesn't match an email pattern, return the item as an error.          return item;       }     } else if (valid != undefined) {       // If the validator is not true or "email", assume it's a regular expression       // string. Create a regular expression from the string and test for a match.       re = new RegExp(valid);       if (!re.test(values[item])) {         // If it doesn't match the reg exp, return the item as an error.          return item;       }     }   }   // Return true to indicate successful validation   return true; };

You can use the validation methods in a form before submitting it. If the validate( ) method returns true, then the form is ready to submit; otherwise, you can direct the user to correct the errors on the form. The following is an example of its use. Note that this example uses a trace( ) statement to display the error in the Output window. However, the Output window is available only when testing during authoring. For more details on how to effectively alert the user with messages when the Flash Player is running in a browser, see Recipe 11.15.

#include "Form.as" // Create two text fields and a push button. _root.createTextField("name_txt", 1, 100, 100, 100, 20); _root.createTextField("email_txt", 2, 100, 130, 100, 20); _root.attachMovie("FPushButtonSymbol", "btn_pb", 3, {_x: 100, _y: 160}); // Set the text fields so that they have a border and allow input. name_txt.border  = true; name_txt.type    = "input"; email_txt.border = true; email_txt.type   = "input"; // Create the form. myForm = new Form(  ); // Add the text fields to the form and set validators for them. The name_txt field // must contain some text, and email_txt must have a valid email format. myForm.addElement(name_txt); myForm.setValidator("name_txt", true); myForm.addElement(email_txt); myForm.setValidator("email_txt", "email"); btn_pb.onRelease = function (  ) {   // Call the validate(  ) method of the form.   var valid = _root.myForm.validate(  );   // If the form validates, submit the form. Otherwise, display the name of the form   // element that needs to be corrected.   if (valid) {     // Submit form.   } else {     trace(valid);   } };

11.14.4 See Also

Recipe 9.6, Recipe 11.12, and Recipe 11.15



ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net