One of these days I had to create a a dynamic form and validate some of its fields which could be TextInput, TextArea, CheckBox or ComboBox and I thought of using Validators do accomplish this but although for TextInput and TextArea you can easily just use the StringValidator for CheckBox and ComboBox is not so easy to choose which one to use.

CheckBox

First I thought of creating a BooleanValidator that extended Validator so I could use it on CheckBoxes but I couldn’t get it to display the red border around the CheckBox when its invalid so I came up with a simple way of doing it. I just used a StringValidator that checks the maxLength property like this:

AS3:

public var validators:Array = new Array();
 
// when adding the validators
var checkboxValidator:StringValidator = new StringValidator();
checkboxValidator.property = 'selected';
checkboxValidator.maxLength = 4;
checkboxValidator.tooLongError = 'Please check it!';
checkboxValidator.source = myCheckboxId;
validators.push(checkboxValidator);
 
// and when validating on submit
for (var i:int; i < validators.length; i++) {
	var src:UIComponent = validators[i].source;
	if (src is CheckBox) validator[i].validate(CheckBox(validators[i].source).selected);
}

Since the value of the “selected” property of the CheckBox is a Boolean it is automatically converted to String so it will be either the String “true” which has 4 characters or the String “false” which has 5 characters, our maxLength is 4 so when the CheckBox is not checked the length will be 5 (“false”) and then be invalid. This actually works better then using a NumberValidator and converting the Boolean false to 0 and true to 1 because it will still display as invalid sometimes because of wrong data type.

ComboBox

For validating the ComboBox I used a NumberValidator and set the minValue to 0 which is the first option in the ComboBox list (none selected is -1) and used the selectedIndex as the property to check for.

AS3:

public var validators:Array = new Array();
 
// when adding the validators
var comboboxValidator:NumberValidator = new NumberValidator();
comboboxValidator.property = 'selectedIndex';
comboboxValidator.minValue = 0;
comboboxValidator.lowerThanMinError = 'Please select one!';
comboboxValidator.source = myComboboxId;
validators.push(comboboxValidator);
 
// and when validating on submit
for (var i:int; i < validators.length; i++) {
	var src:UIComponent = validators[i].source;
	if (src is ComboBox) validator[i].validate(ComboBox(validators[i].source).selectedIndex);
}

Hope this helps anyone, I’ll try to make a post soon about creating a class to generate forms dynamically and validating them.