这是这个问题的后续问题:How does DataAnnotations really work in MVC? 有一个示例自定义验证,并提到了“自我验证模型”。这很有意思,但我不明白如何为它编写客户端验证。
我的模型对象可以实现IClientValidateble接口(或仅用于dataannotation属性吗?),我想看一个如何做的例子。
编辑:根据我的理解,“自我验证模型”在不使用DataAnnotations的情况下工作,并在类中声明了我正在验证属性的验证逻辑,并且它(不一定)使用属性来验证某些内容。
我在自定义客户端验证中看到的所有示例都是关于实现IClientValidatable的dataannotation 属性。
当我在课堂上声明我的验证逻辑时,我不使用属性来验证模型的状态。
当我在实现IValidatebleObject接口的模型类的Validate方法中声明验证逻辑时,如何编写客户端验证?
我实际传递给视图的类可以实现IClientValidatable接口或类似的东西吗?
答案 0 :(得分:2)
采取相同的答案:
实施自我验证模型后,您需要创建客户端验证部分,为此,只需创建以下3个步骤:
附加到IClientValidateble
班级
public IEnumerable<ModelClientValidation> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelCLientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "greater"; // This is what the jQuery.Validation expects
rule.ValidationParameters.Add("other", OtherPropertyName); // This is the 2nd parameter
yield return rule;
}
然后,您需要编写新的 jQuery Validator 和元数据适配器,它将jQuery.Validation与您的代码相关联,为您提供正确的data-
属性该字段(当然,如果UnobtrusiveJavaScriptEnabled
为真)
创建一个新的js
文件并附加到<head>
,例如
<script src="@Url.Content("~/Scripts/customValidation.js")" type="text/javascript"></script>
并附加新的验证
jQuery.validator.addMethod("greater", function(value, element, param) {
// we need to take value and compare with the value in 2nd parameter that is hold in param
return Date.parse(value) > Date.parse($(param).val());
});
然后我们编写适配器
jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function(options) {
// pass the 'other' property value to the jQuery Validator
options.rules["greater"] = "#" + options.param.other;
// when this rule fails, show message that comes from ErrorMessage
options.messages["greater"] = options.message;
});
您可以在创建新的MVC3 Web Applicatoin时在AccountModel.cs
中查看此内容,它会显示实现IClientValidatable
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
{
private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
public ValidatePasswordLengthAttribute()
: base(_defaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
name, _minCharacters);
}
public override bool IsValid(object value)
{
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= _minCharacters);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[]{
new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
};
}
}
#endregion