【问题标题】:Custom data annotation validation on Client Site : $.validator.addMethod error客户端站点上的自定义数据注释验证:$.validator.addMethod 错误
【发布时间】:2018-05-28 16:07:21
【问题描述】:

从这个answer 我已经从这个博客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 };
    }
}

这是我在 View 中使用的代码:

剃刀代码:

 @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));

【问题讨论】:

  • 不要根据答案改变你的问题!我已回滚您的更改。
  • 谢谢,@StephenMuecke 我正在编辑,因为我已将其放入我的代码中但甚至无法正常工作,所以,我只是在测试你所说的内容,然后在你来到这里时评论你的答案意味着什么:)。我刚测试完就来了,再次问你:)
  • 我给出的答案是正确的。我完全照原样复制了您的代码,得到了那个错误,然后修改了属性以实现 IClientValidatable 并且错误消失,data-val- 被渲染并且客户端验证完美运行

标签: jquery asp.net-mvc-5 jquery-validate data-annotations unobtrusive-validation


【解决方案1】:

您的自定义属性未实现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 ($) {

【讨论】:

  • 这是我检查过的 LastUpdate 文本框代码: 但不幸的是我的客户端验证甚至无法正常工作
  • 那你把相关的脚本都加进去了吗? - jquery-{version}.js,然后是 jquery.validate.jsjquery.validate.unobtrusive.js(它们必须在你的脚本之前。
  • 即使我已经删除了 (function($){ 部分并将其放入 $(document).ready(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"); });
  • 不要不要使用(function($){ $(document).ready(function() {
  • 是的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多