Input validation could help improve application responsiveness and usability, but it's sometimes ignored by developers.
Flex has a slew of built-in validators that could help you validate a field with one line of MXML. For complex validations, there's also a regular expression validator at your disposal.
Flex has a set of Validator classes which can be used to validation data entries. The Validator class is the base for all other validator classes. The complete list of validators cover the following,
To use validation, instantiate a validation sub class for each target field. For instance, consider this Text Input control,
To ensure that a number is entered into this field, instantiate the validator class as follows,
Note: by default, the validation fails if the field is empty. If you wish to validate a field only if data is entered, set the “required” property to false as follows,
Once a validation is instanciated, it should be attached to an event. Normally, validation is attached to the field’s “focusOut” event.
Each validator sub class has a set of attributes that let’s you fine tune the validation. For example, for NumberValidator, I could set the “minValue” and “maxValue”. Please consult the Flex documentation for a complete list of validation attributes.
If none of the validation sub classes match your needs, consider using the RegExpValidator class. Regular expression allows you to perform complex pattern matching on strings. The Canadian postal code, for example, is formated like “K1N 2P6″. The default US zip code validator would not work. Instead, we could use the regular expression validator as follows,
The regular expression validator also sports a number of flags to further enrich the regular expression. For instance, to turn off case sensitivity, just set the flag to “i”,