我第一次尝试编写自己的验证脚本。我已经学习了几个教程,并且已经让它们工作,现在试图从头开始理解它背后的逻辑,这是我的自定义一个:
属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DateGreaterThanTodayAttribute: ValidationAttribute, IClientValidatable
{
public DateGreaterThanTodayAttribute(): base("{0} must be greater than today")
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var valueAsDate = (DateTime)value;
if (valueAsDate < DateTime.Now)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "dategreaterthantoday";
rule.ValidationParameters.Add("today", DateTime.Now);
yield return rule;
}
}
}
JS:
$.validator.addMethod("dategreaterthantoday", function (value, element, params) {
if (value) {
var valueAsDate = Date.parse(value);
if (valueAsDate < Date.now)
return false;
}
return true;
});
$.validator.unobtrusive.adapters.addBool("dategreaterthantoday")
服务器端验证工作正常,但我仍然对必须在客户端代码上传递的参数感到有点困惑,如果有人可以帮助我理解为什么客户端验证不起作用,我不只是在寻找一个简单的解决方案,但解释了我做错了什么以及如何解决它。
提前致谢!