客户端站点上的自定义数据注释验证:$.validator.addMethod 错误

Custom data annotation validation on Client Site : $.validator.addMethod error

从此answer I have write my code from this blog DevTrends执行自定义数据注释验证。但是在 $.validator.addMethod( ) 方法的客户端站点中出现如下图所示的错误。请帮我解决这个问题。

message  :"value is not defined"
stack  : "ReferenceError: value is not defined↵    at eval (eval at <anonymous> (http://localhost:61052/boatproduction/edit/2?pg=1&sz=10&st=id&dr=desc:71:13), <anonymous>:1:1)↵    at http://localhost:61052/boatproduction/edit/2?pg=1&sz=10&st=id&dr=desc:1279:13↵    at http://localhost:61052/boatproduction/edit/2?pg=1&sz=10&st=id&dr=desc:1288:10" 

我的视图模型如下

   public class BoatProductionModel
{
    public long Id { get; set; } 
    public DateTime StartDate { get; set; }        
    [DateComparison("StartDate")]
    public DateTime LastUpdate { get; set; }       
    public int? NumberOfEmployee { get; set; }        
}


[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class DateComparison : ValidationAttribute
{
    private const string DefaultErrorMessage = "{0} cannot be the same as {1}.";
    public string OtherProperty { get; private set; }

    public DateComparison(string otherProperty)
      : base(DefaultErrorMessage)
    {
        if (string.IsNullOrEmpty(otherProperty))
        {
            throw new ArgumentNullException("otherProperty");
        }

        OtherProperty = otherProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, OtherProperty);
    }

    protected override ValidationResult IsValid(object value,
                          ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType()
                               .GetProperty(OtherProperty);

            var otherPropertyValue = otherProperty
                          .GetValue(validationContext.ObjectInstance, null);

            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(
                  FormatErrorMessage(validationContext.DisplayName));
            }
        }
        return null;  //return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> 
GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var clientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "notequalto"
        };

        clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty);

        return new[] { clientValidationRule };
    }
}

这是我在视图中使用的代码:

剃须刀代码:

 @model  Data.AppModels.BoatProductionModel
 @Html.TextBoxFor(model => model.LastUpdate, "{0:MM/dd/yyyy}", new { @class = "form-control pull-right", placeholder = "Last Update"    })
 @Html.ValidationMessageFor(model => model.LastUpdate)

JavaScript代码:

(function ($) {
            $.validator.addMethod("notequalto", function (value, element, params) {
                if (!this.optional(element)) {
                    var otherProp = $('#' + params)
                    return (otherProp.val() != value);
                }
                return true;
            });
            $.validator.unobtrusive.adapters.addSingleVal("notequalto", "otherproperty");

        }(jQuery));

您的自定义属性未实现 IClientValidatable(尽管您包含了该接口中定义的 GetClientValidationRules() 方法。因此,未生成与您的属性关联的 data-val-* 属性在 html 中,因此 jquery.validate.unobtrusive.js 不会将规则添加到 jquery.validate.js

将验证属性的签名更改为

public sealed class DateComparison : ValidationAttribute, IClientValidatable
{
    ....
}

您输入的 html 现在将包含以下属性

data-val-notequalto="LastUpdate cannot be the same as StartDate." data-val-notequalto-otherproperty="StartDate"

将由 jquery.validate.unobtrusive.js 解析。

另请注意,您不需要将脚本包装在 (function ($) {