采取了相同的答案:
后你实现自我验证模型,女巫是一个服务器端验证,你需要创建客户端验证部分,对于这一点,只需创建此3个步骤:
- 实施
- 实现一个jQuery验证方法
- 实现一个不显眼的适配器
追加到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的验证和元数据适配器将链接jQuery的。验证你的代码提供正确的data-
属性该字段(如果当然,UnobtrusiveJavaScriptEnabled
为true)
创建一个新的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;
});
当你创建一个新的Web MVC3您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
我更新的问题更加清晰。 – SoonDead 2011-03-01 15:06:50
这显然不像以前那样是一回事,因为在这里他会询问是否可以在每个属性上使用IClientValidatable WITHOUT(dataannotain)属性!你的答案包含'public sealed class ValidatePasswordLengthAttribute:ValidationAttribute,IClientValidatable',所以这显然不是一个正确的答案! – TDaver 2011-03-04 12:56:13