MVC 验证和异常处理 实现自定义客户端验证逻辑
以实现[EqualToProperty] 为例。
A,首先定义一个继承自ModelValidator的类并重写GetClientValidationRules方法。
public class EqualToPropertyValidator : ModelValidator
{
// ... rest as before
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var clientValidationRule = new ModelClientValidationRule {
ValidationType = "EqualToProperty",
ErrorMessage = "This value must equal the value of " + compareProperty
};
clientValidationRule.ValidationParameters["compareTo"] = compareProperty;
yield return clientValidationRule;
}
}
B,客户端添加自定义js验证逻辑
<script type="text/javascript">
Sys.Mvc.ValidatorRegistry.validators.EqualToProperty = func
// Prepare by extracting any parameters sent from the s
var compareProperty = rule.ValidationParameters.compare
// Return a function that tests a value for validity
return function (value, context) {
// Find the comparison element by working out what its name must be
var thisElement = context.fieldContext.elements[0];
var compareName = thisElement.name.replace(/[^\.]*$/, compareProperty);
var compareElement = document.getElementsByName(compareName)[0];
// Check that their values match
return value == compareElement.value;
}
};
</script>
注意标红处,名称要和自定义EqualToPropertyValidator匹配。
js验证方法会接收到两个参数,第一个从字面就知道是干什么的。第二个context对象详细解释如下:
Property |
Description |
eventName |
Takes one of three values: input, when the user is currently typing into the field; blur, when the user has just moved the focus away from the field; and submit, when the user has just asked for the form to be submitted. This lets you choose when to make a validation error message appear. For example, you could write if(context.eventName != 'submit') return true; to mean that your validation message should not appear until the user tries to submit the form. Note that, to avoid displaying error messages too early, input events don’t fire until either a blur or a submit event has already fired at least once. Also note that, due to Internet Explorer quirks, the input event doesn’t fire on Internet Explorer 7 or earlier—it only works on Internet Explorer 8+ or other major browsers. |
fieldContext .elements |
An array of HTML DOM nodes that are associated with your validator. Typically this will contain just one element—the form field whose value you are validating. |
fieldContext .validationMessageElement |
The HTML DOM node that will be used to display any validation message for this validator. |
fieldContext .formContext .fields |
An array containing all the fieldContext objects associated with the form. You can use this to inspect the state of other validators in the same form. |