URLValidator for AS3/Flex

I had the need for a URL Validator for a Flex project, and couldn’t find one. So, here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package org.iotashan.validators
{
    import mx.validators.ValidationResult;
    import mx.validators.Validator;
   
    public class URLValidator extends Validator
    {
        public function URLValidator()
        {
            super();
        }
       
        override protected function doValidation(value:Object):Array
        {
            // Clear results Array.
            var results:Array = [];

            // Call base class doValidation().
            results = super.doValidation(value);       
            // Return if there are errors.
            if (results.length > 0)
                return results;
           
            // match regex pattern
            var pattern:RegExp = new RegExp("^http[s]?\:\\/\\/([^\\/]+)\\/");
            // run the pattern, but don't error if there is no value and this is not required
            if (!(!required && !value) && !pattern.exec(String(value))) {
                results.push(new ValidationResult(true, null, "notURL",
                    "You must enter a valid URL."));
                return results;
            }
           
            return results;
        }
    }
}

You can download the swc here.

Comments