Skip to content
September 22, 2008 / Shrikant Patil

Flex : Creating Custom Validators

Flex Framework included a very useful component called Validator. The component can be used to validate the data of user input. There are standard validator types of components available like NumberValidator, StringValidator, DataValidator etc. According to the custom needs of application development, the situations arises to develop a custom validator.

All standard validators components inherits from the base of mx.Validators.Validator class. To create a custom validator need to work with extending the Validator class. The creation of custom validator includes following steps;

A) Create a class which extends mx.Validators.Validator.

B) Class must override doValidation() method.

C) Overridden doValidation() method should accept a parameter of type Object.

D) Overridden doValidation() method should return an Array.

If the validation of a condition against given object doesn’t succeed, then doValidation() method returns an array containing objects of ValidationResult. If doValidation() method does succeed then method returns an empty array. To validate a condition against the user input, we need to take use of RegExp Object.

Here is a sample of IPAddressValidator class:


package flexScript
{
     import mx.validators.ValidationResult;
     import mx.validators.Validator;

 //Class should extend mx.validators.Validator
 public class IPAddressValidator extends Validator {

        public function IPAddressValidator() {
            // Call base class constructor.
            super();
        }

        // Class should override the doValidation() method.
        //doValidation method should accept an Object type parameter
        override protected function doValidation(value:Object):Array {
            // create an array to return.
            var ValidatorResults:Array = new Array();
            // Call base class doValidation().
            ValidatorResults = super.doValidation(value);       
            // Return if there are errors.
            if (ValidatorResults.length > 0)
                return ValidatorResults;

            if (String(value).length == 0)
             return ValidatorResults;

               var RegPattern:RegExp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
            var a:Array = RegPattern.exec(String(value));
               if (a == null)
               {
                ValidatorResults.push(new ValidationResult(true, null, "IPAddress Error","You must enter an IP Address"));
                return ValidatorResults;
               }
             return ValidatorResults;
        }
    }
}

once we have done with creating the custom validator, we can use it as standard validator.
Below is the MXML code which uses the IPAddressValidator to validate the entered IP address.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns:com="*" xmlns:flexScript="flexScript.*">
<mx:Form>
<mx:FormHeading label="IP Validator"/>
<mx:FormItem label="Enter IP Address">
<mx:TextArea id="IPInput" />
</mx:FormItem>
<mx:FormItem>
<mx:Button id="button" label="Submit"/>
</mx:FormItem>
</mx:Form>

<flexScript:IPAddressValidator source="{IPInput}" property="text"/>
</mx:Application>

About these ads

12 Comments

Leave a Comment
  1. vivek / Oct 13 2008 12:19 pm

    how can we change the color of the default validator’s message popup and i dont want red bordered box, instead i need some orange filled box. is it possible?

    -vivek

  2. Shrikant Patil / Oct 13 2008 1:37 pm

    HI,
    you can change the colors of pop up error message background color & border color of inputText (Default it is red). for you i am placing a sample code below which will give overall idea.

    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
    layout=”vertical”
    verticalAlign=”middle”
    backgroundColor=”white”>

    <mx:Style>
    .errorTip {
    borderColor: #3300FF;
    color: black;
    fontSize: 16;
    fontWeight: normal;
    }

    TextInput {
    errorColor: #3300FF;
    }
    </mx:Style>

    <mx:TextInput id=”textInput”
    errorString=”Different Color Error” />
    </mx:Application>

    Hope this helps you.

  3. Jim Schell / Oct 17 2008 8:01 pm

    I was wondering if it is possible to call a custom validator based on a sql select statement.

    I have an application that allows the end user to create sql statements which are joined togethor in a union select query, this is then run after all the data is inserted.

    I would like to do instant validation based on user input when they exit the field using user defined sql select statements

    Any suggestions

    Thanks

    Jim

  4. Shrikant Patil / Oct 18 2008 5:14 am

    HI,
    I think you can achieve this using custom validators. Only the thing is you need to create your custom validator according to your requirements, which check exact sql statements entered. you can use the same procedure used in above post to create your custom validators. you need to use RegExp object to check the user input. I think you can achieve this.

  5. Nash / Jun 7 2009 7:41 pm

    One example for Custom Date validation in flex

    http://yasob.blogspot.com/2009/06/flex-custom-date-validation.html

  6. Cynthia / Sep 14 2009 9:28 pm

    Thanks for the write-up.

    I have a validation class that uses dispatched events to let other classes know when it’s finished doing the validation it needs to do. This is because sometimes my validation requires that I go to the server and ask the server if the data is valid. Is there a way to build a custom validator that will allow me to listen for the event to be thrown from that class and then populate the doValidation array for return? This would be a synchronous process, I understand, and Flex isn’t great with it. Just figured someone must have dealt with something like this before…

    Thanks!

    • Shrikant Patil / Sep 15 2009 5:21 am

      you send the data to be validated to server, once you get the response using HTTPServices or some other object (Which are basically used to send and get data from server) you can call DoValidate method manually. that can be done i guess.

  7. Sunshine Dudasik / Sep 8 2011 5:35 am

    This would have to be a new blog. Something that you want to read about, but havent found online. This can be religious, fashion-based, etc. Im just getting some ideas for the blog i want to start- Thanks!.

  8. Hello / Oct 3 2011 2:18 pm

    Why is “ValidatorResults” capitalized? So much for naming standards… duhhhh

  9. Hello / Oct 3 2011 2:26 pm

    And “RegPattern” is capitalized why? Please, let’s not throw conventions out the window in examples, leading people to believe there’s a “RegPattern” class with public static methods or some such!

  10. persuasion / May 22 2013 8:07 pm

    An interesting discussion is worth comment.
    I do believe that you ought to write more about this subject,
    it may not be a taboo matter but usually people don’t discuss such topics. To the next! Kind regards!!

  11. online degree business management / May 29 2013 5:43 pm

    I constantly spent my half an hour to read this webpage’s content daily along with a cup of coffee.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: