The following example shows you how you can validate email addresses in a Flex application using the EmailValidator class and the validate() and static EmailValidator.validateEmail() methods.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/29/validating-email-addresses-using-the-emailvalidator-class-in-flex/ -->
<mx:Application name="EmailValidator_validate_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;

            private function emailValidator_valid(evt:ValidationResultEvent):void {
                textInput.errorString = "";
                message.text = "";
                Alert.show(textInput.text, "You entered a valid email address:");
            }

            private function emailValidator_invalid(evt:ValidationResultEvent):void {
                textInput.errorString = evt.message;
                message.text = evt.message;
            }

            private function btn_click(evt:MouseEvent):void {
                emailValidator.validate(textInput.text);
            }
        ]]>
    </mx:Script>

    <mx:EmailValidator id="emailValidator"
            valid="emailValidator_valid(event);"
            invalid="emailValidator_invalid(event);" />

    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="email address:"
                direction="horizontal">
            <mx:TextInput id="textInput"
                    focusAlpha="0.5" />
            <mx:Button id="btn"
                    label="validate"
                    click="btn_click(event);" />
        </mx:FormItem>
    </mx:Form>
    <mx:Label id="message" />

</mx:Application>

View source is enabled in the following example.

The following example shows how you can create an EmailValidator object using ActionScript:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/29/validating-email-addresses-using-the-emailvalidator-class-in-flex/ -->
<mx:Application name="EmailValidator_validate_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import mx.validators.EmailValidator;
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;

            private var emailValidator:EmailValidator;

            private function init():void {
                emailValidator = new EmailValidator();
                emailValidator.addEventListener(ValidationResultEvent.VALID, emailValidator_valid);
                emailValidator.addEventListener(ValidationResultEvent.INVALID, emailValidator_invalid);
            }

            private function emailValidator_valid(evt:ValidationResultEvent):void {
                textInput.errorString = "";
                message.text = "";
                Alert.show(textInput.text, "You entered a valid email address:");
            }

            private function emailValidator_invalid(evt:ValidationResultEvent):void {
                textInput.errorString = evt.message;
                message.text = evt.message;
            }

            private function btn_click(evt:MouseEvent):void {
                emailValidator.validate(textInput.text);
            }
        ]]>
    </mx:Script>

    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="email address:"
                direction="horizontal">
            <mx:TextInput id="textInput"
                    focusAlpha="0.5" />
            <mx:Button id="btn"
                    label="validate"
                    click="btn_click(event);" />
        </mx:FormItem>
    </mx:Form>
    <mx:Label id="message" />

</mx:Application>

The following example shows how you can validate an email address using the static EmailValidator.validateEmail() method and then loop over the array of returned ValidationResult objects:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/29/validating-email-addresses-using-the-emailvalidator-class-in-flex/ -->
<mx:Application name="EmailValidator_validate_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import mx.validators.ValidationResult;
            import mx.validators.EmailValidator;
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;

            private var emailValidator:EmailValidator;

            private function init():void {
                emailValidator = new EmailValidator();
            }

            private function btn_click(evt:MouseEvent):void {
                var arr:Array = EmailValidator.validateEmail(emailValidator, textInput.text, "text");
                var obj:ValidationResult;
                if (arr.length > 0) {
                    obj = arr[0] as ValidationResult;
                    textInput.errorString = obj.errorMessage;
                    message.text = obj.errorMessage;
                } else {
                    textInput.errorString = "";
                    message.text = "";
                    Alert.show(textInput.text, "You entered a valid email address:");
                }
            }
        ]]>
    </mx:Script>

    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="email address:"
                direction="horizontal">
            <mx:TextInput id="textInput"
                    focusAlpha="0.5" />
            <mx:Button id="btn"
                    label="validate"
                    click="btn_click(event);" />
        </mx:FormItem>
    </mx:Form>
    <mx:Label id="message" />

</mx:Application>

The following example shows how you can validate an email address by creating an EmailValidator object in MXML and then specifying the source, property, trigger, and triggerEvent properties:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/29/validating-email-addresses-using-the-emailvalidator-class-in-flex/ -->
<mx:Application name="EmailValidator_validate_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;

            private function emailValidator_valid(evt:ValidationResultEvent):void {
                textInput.errorString = "";
                message.text = "";
                Alert.show(textInput.text, "You entered a valid email address:");
            }

            private function emailValidator_invalid(evt:ValidationResultEvent):void {
                textInput.errorString = evt.message;
                message.text = evt.message;
            }
        ]]>
    </mx:Script>

    <mx:EmailValidator id="emailValidator"
            valid="emailValidator_valid(event);"
            invalid="emailValidator_invalid(event);"
            source="{textInput}"
            property="text"
            trigger="{btn}"
            triggerEvent="click" />

    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="email address:"
                direction="horizontal">
            <mx:TextInput id="textInput"
                    focusAlpha="0.0" />
            <mx:Button id="btn"
                    label="validate" />
        </mx:FormItem>
    </mx:Form>
    <mx:Label id="message" />

</mx:Application>

The following example shows how you can validate an email address by creating an EmailValidator object using ActionScript and then specifying the source, property, trigger, and triggerEvent properties:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/29/validating-email-addresses-using-the-emailvalidator-class-in-flex/ -->
<mx:Application name="EmailValidator_validate_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">

    <mx:Style>
        @font-face {
            src: local("Verdana");
            fontFamily: VerdanaEmbedded;
            fontWeight: bold;
        }

        .errorMessage {
            fontFamily: VerdanaEmbedded;
            fontWeight: bold;
        }

        .validTextInputStyle {
            backgroundAlpha: 0.6;
            backgroundColor: haloGreen;
        }

        .invalidTextInputStyle {
            backgroundAlpha: 0.3;
            backgroundColor: red;
        }
    </mx:Style>

    <mx:Script>
        <![CDATA[
            import mx.validators.EmailValidator;
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;

            private var emailValidator:EmailValidator;

            private function init():void {
                emailValidator = new EmailValidator();
                emailValidator.source = textInput;
                emailValidator.property = "text";
                emailValidator.trigger = btn;
                emailValidator.triggerEvent = MouseEvent.CLICK;
                emailValidator.addEventListener(ValidationResultEvent.VALID, emailValidator_valid);
                emailValidator.addEventListener(ValidationResultEvent.INVALID, emailValidator_invalid);
            }

            private function emailValidator_valid(evt:ValidationResultEvent):void {
                textInput.errorString = "";
                textInput.styleName = "validTextInputStyle";
                Alert.show(textInput.text, "You entered a valid email address:");
            }

            private function emailValidator_invalid(evt:ValidationResultEvent):void {
                textInput.errorString = evt.message;
                textInput.styleName = "invalidTextInputStyle";
                message.visible = true;
                message.text = evt.message;
                message.visible = false;
            }
        ]]>
    </mx:Script>

    <mx:Fade id="dissolveEffect"
            startDelay="1500"
            alphaFrom="1.0"
            alphaTo="0.0" />

    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="email address:"
                direction="horizontal">
            <mx:TextInput id="textInput"
                    focusAlpha="0.5" />
            <mx:Button id="btn"
                    label="validate" />
        </mx:FormItem>
    </mx:Form>
    <mx:Label id="message"
            styleName="errorMessage"
            hideEffect="{dissolveEffect}" />

</mx:Application>

View source is enabled in the following example.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

9 Responses to Validating email addresses using the EmailValidator class in Flex

  1. Spanky says:

    Is there an easy way to validate two textInputs for email (as in, confirmation that the user typed their email address of hotmama22@hotmail.com instead hotmama2@hotmail… assuming that they won’t mistype it the same way twice)?

  2. Anonymous says:

    Is there any way to validate emails like xxxxx.o’xxxxxx@domain.com. It is a valid email. I need to turns on strict interpretation in flex too.
    In java email , it can be done as ———– new InternetAddress(vcea.get(i).emailaddr, true );

  3. Lp Bell says:

    Ok!! i found an online validator tool (for free) but it only does headers validation..
    Not sure if it would work on a site..

    Help?

    http://www.convincingmail.com/emailvalidation.aspx

  4. Bart says:

    When I’m typing in a flash input field and a use the @-sign, it completely blocks the typing. I noticed it on my own site and now in your example. I tried it on a diverent computer with the same result. In a HTML field there’s no problem.
    Is it me or some thing in the Flash player?
    Help?
    BTW, I like your examples a lot! Thanks!

  5. LesBerg says:

    The third example doesn’t work for me. If the email address fails the validation for any reason, it always returns the error message:

    “An at sign (@) is missing in your e-mail address.”

    This time, the address submitted was “gwergwe@@erth.com”

  6. LesBerg says:

    It turns out that I had to change the line (modeled from your third example)

    from
    var evResults:Array = EmailValidator.validateEmail(emailValidator, tbNewEmailAddress, ‘text’);

    to var evResults:Array = EmailValidator.validateEmail(emailValidator, tbNewEmailAddress.text, ‘text’);

    and it works as expected

  7. Anonymous says:

    what if i want to add multiple email ids..

  8. sanya says:

    i want my email text field to accept more than one eamil id…with seperator “,”
    ex-abc@xyz.com,abc@yahoo.com,abc@gmail.com