有以下 2 个电子邮件字段,首先我们定义一个标准电子邮件验证器,然后我们定义一个附加在答案末尾的自定义电子邮件验证器进行确认。
<mx:HBox
verticalAlign = "middle"
color = "#101010">
<mx:Label
text = "E-Mail Address:"
width = "120"/>
<mx:TextInput
id = "txtEmail"
width = "220"/>
</mx:HBox>
<mx:HBox
verticalAlign = "middle"
color = "#101010">
<mx:Text
text = "Rewrite E-Mail Address:"
width = "120"/>
<mx:TextInput
id = "txtEmail2"
width = "220"/>
</mx:HBox>
现在我们添加验证器
<mx:EmailValidator
id = "valEmail"
required = "true"
source = "{txtEmail}"
property = "text"
invalidCharError = "Invalid format"
invalidDomainError = "Invalid format"
invalidIPDomainError = "Invalid format"
invalidPeriodsInDomainError = "Invalid format"
missingAtSignError = "Invalid format"
missingPeriodInDomainError = "Invalid format"
missingUsernameError = "Invalid format"
/>
<validators:EmailConfirmationValidator
id = "valEmail2"
required = "true"
source = "{txtEmail2}"
property = "text"
confirmationSource = "{txtEmail}"
confirmationProperty= "text"/>
另外,我们需要定义我在“验证器”包中声明的 EmailConfirmationValidator 类
package validators
{
import mx.validators.ValidationResult;
import mx.validators.Validator;
public class EmailConfirmationValidator extends Validator
{
public var confirmationSource: Object;
public var confirmationProperty: String;
public function EmailConfirmationValidator()
{
super();
}
// Define the doValidation() method.
override protected function doValidation(value:Object):Array
{
// Call base class doValidation().
var results:Array = super.doValidation(value);
if (value.text != value.confirmation)
{
results.push(new ValidationResult(true, null, "Mismatch",
"Emails do not match!"));
}
return results;
}
/**
* @private
* Grabs the data for the confirmation password from its different sources
* if its there and bundles it to be processed by the doValidation routine.
*/
override protected function getValueFromSource():Object
{
var value:Object = {};
value.text = super.getValueFromSource();
if (confirmationSource && confirmationProperty)
{
value.confirmation = confirmationSource[confirmationProperty];
}
return value;
}
}
}
如果您需要手动检查表单中的验证器。例如在提交内容进行注册之前,使用以下方法
public function isValid():Boolean
{
var validators:Array = [valEmail, valEmail2];
var validatorErrorArray:Array = Validator.validateAll(validators);;
var isValidForm:Boolean = validatorErrorArray.length == 0;
return isValidForm;
}