11.5 Adding Validation to a TextField

Text fields are used often in Flash Remoting applications, because you frequently need to accept user input for your remote calls. Any time a user can interact with an application, the possibility exists for major problems. One way to minimize the types of problems you might encounter is to validate the user-input data before it is sent to the remote server.

Client-side validation is important for a smooth user experience, but you should also validate user-input data on the server, to avoid malicious attacks on your server-side services. Remember, when you set up a remote service, it is open to the world, whether a user uses your Flash interface or not.

The next example shows how you might implement a validation routine directly on the TextField class. (The TextField component on the DRK 3 CD-ROM also features validation functionality.) Simply calling TextField.validate( ) causes all text fields that have a defined validator to be validated. The method returns an error message if there is a problem, or nothing if everything validates properly. First, enhance the TextField class to keep track of the validators for each TextField instance. The validators are stored in an array:

TextField.validators = new Array( );

Next, insert a routine to allow the programmer to set a specific validator type on a given text field:

TextField.prototype.setValidationType = function (theType, errMsg) {
  var validator = new Object( );
  validator.textfield = this;
  validator.theType = theType;
  validator.errMsg = errMsg;
  // If validator needs more arguments, set them up here
  if (arguments.length > 2) {
    for (var i=2; i< arguments.length; i++) {
      validator[i] = arguments[i];
    }
  }

  TextField.validators.push(validator);
};

The setValidationType( ) method allows two or more arguments. The first argument, theType, specifies the type of validation. The errMsg argument allows you to set the error message. If you supply more than two arguments, the remaining arguments will be passed to the validate( ) method for use by the given validation routine.

Finally, create the validation routines in the validate( ) method. Because this is a simple example, I've implemented only a required field, an email field, a password field between n and n2 characters (arguments 3 and 4 are passed to the setValidationType( ) method), and a password confirmation validator (using argument 3 passed to setValidationType( )). More case statements could be added for more validation types:

TextField.validate = function ( ) {
  var errMsg = "";
  var temp;
  for (var i=0; i < this.validators.length; i++) {
    temp = this.validators[i];
    switch(temp.theType) {
      case 0:
        break;
      case 1:       // required field
        if (temp.textfield.text == "")
          errMsg += temp.errMsg + "\n";
        break;
      case 2:       // email address
        if (!isValidEmail(temp.textfield.text))
          errMsg += temp.errMsg + "\n";
        break;
      case 3:       // password between n and n2 characters
        if (temp.textfield.text.length < temp["2"] ||
           temp.textfield.text.length > temp["3"])
          errMsg += temp.errMsg + "\n";
        break;
      case 4:       // password must equal confirm fields
        if (temp.textfield.text != temp["2"].text)
          errMsg += temp.errMsg + "\n";
        break;
    }
  }
  function isValidEmail (theString) {
    var isValid = (
     (theString.lastIndexOf('.') < theString.length - 2) && // must have dot
     (theString.indexOf('@') != -1) &&                      // must have one @
     (theString.indexOf('@') == theString.lastIndexOf('@')) // must not have two @@
     )
     return isValid;
  }
  return errMsg;
};

To demonstrate the new method of the TextField class, set up a new movie with four input text fields named name_txt, email_txt, password_txt, and confirm_txt, along with a Submit button and a MessageBox component named validation_mb (from UI Components Set 2). Here is the code to set up the validators on the boxes:

name_txt.setValidationType(1, "Name must not be blank");
email_txt.setValidationType(2, "Email must be valid");
password_txt.setValidationType(3, "Password must be between 8 and 12 characters",
                               8, 12);
password_txt.setValidationType(4, "Passwords don't match", confirm_txt);

Each TextField that is to be validated is initialized with the setValidationType( ) method, with two arguments. Simply pass the number of the validation type (1: required field; 2: email validation; 3: password of a given length, 4: password match). The password_txt field actually has two validations on it: a length validation and a confirmation validation. The code to submit the form and check the validity of the data is shown here:

submit_pb.setClickHandler("submitForm");
submitForm = function ( ) {
  // Validate all TextFields
  var errorMessage = TextField.validate( );
  // If there is an error message, there was a problem
  if (errorMessage != "") {
    validation_mb._visible = true;
    validation_mb.setMessage("Error in the data you provided\n" + errorMessage)
  } else { // No problem, pass the form to the remote method, when implemented
    trace("valid data!!!")
  }
};

There are other ways to perform validations, but this technique shows how you might implement a validator that performs all required validations at one time, by simply enhancing the TextField class.



    Part III: Advanced Flash Remoting
     
    ASPTreeView.com
     
    Evaluation has ПИГДАШМСexpired.
    Info...