为自定义属性创建AddValidation方法继承IClientModelValidator

时间:2018-03-23 20:44:07

标签: jquery validation asp.net-core

我实现自定义属性以确保两个表单值不相等 有一个类似的解决方案,在这里对ASP.NET Core不起作用 mvc3 validate input 'not-equal-to'

 public class NotEqualAttribute : ValidationAttribute, IClientModelValidator
    {

            public string OtherProperty { get; private set; }
            public NotEqualAttribute(string otherProperty)
            {
                OtherProperty = otherProperty;
            }

            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                var property = validationContext.ObjectType.GetProperty(OtherProperty);
                if (property == null)
                {
                    return new ValidationResult(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "{0} is unknown property",
                            OtherProperty
                        )
                    );
                }
                var otherValue = property.GetValue(validationContext.ObjectInstance, null);
                if (object.Equals(value, otherValue))
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
                return null;
            }


        }
}

如何实现IClientValidator AddValidation()方法以使用以下jQuery?我已验证该属性在服务器端正常运行

<script type="text/javascript">
    jQuery.validator.unobtrusive.adapters.add(
        'notequalto', ['other'], function (options) {
            options.rules['notEqualTo'] = '#' + options.params.other;
            if (options.message) {
                options.messages['notEqualTo'] = options.message;
            }
    });

    jQuery.validator.addMethod('notEqualTo', function(value, element, param) {
        return this.optional(element) || value != $(param).val();
    }, '');
</script>

编辑: 我得到了一个解决方法,而是让NotEqualAttribute类继承自`CompareAttribute&#39;。这让我可以取消jQuery片段。但是,如果有人能引导我如何使用不引人注意的jQuery验证作为替代,我会感兴趣

public class NotEqualAttribute : CompareAttribute
    {
        public string BasePropertyName { get; private set; }
        private const string DefaultErrorMessage = "'{0}' and '{1}' must not be the same.";
        public NotEqualAttribute(string otherProperty)
        : base(otherProperty)
    {
            BasePropertyName = otherProperty;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(DefaultErrorMessage, name, BasePropertyName);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = base.IsValid(value, validationContext);
            if (result == null)
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }
}

0 个答案:

没有答案