代码之家  ›  专栏  ›  技术社区  ›  Shadam

JQuery自定义验证属性MVC核心

  •  2
  • Shadam  · 技术社区  · 8 年前

    我尝试添加一个自定义属性来验证所需字段,并修剪空白值。

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class CustomRequired : ValidationAttribute, IClientModelValidator
    {
        public CustomRequired()
        {
            ErrorMessage = new ResourceManager(typeof(ErrorResource)).GetString("All_Required");
        }
    
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
    
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-customrequired", ErrorMessage);
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return value.ToString().Trim().Length > 0 ? ValidationResult.Success : new ValidationResult(ErrorMessage);
        }
    
        private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }
    

    下面是我如何添加(或尝试):

    $(document).ready(function () {
        $.validator.addMethod("customrequired", function (value, element, parameters) {
            return $.trim(value).length > 0;
        });
        $.validator.unobtrusive.adapters.addBool('customrequired');
    });
    

    [CustomRequired]
    public string Code { get; set; }
    

    enter image description here

    enter image description here

    编辑:

    我忘了说我在使用剑道…请看下面我自己的答案。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Shadam    8 年前

    我忘了说我在用剑道。。。

    我的代码具有经典验证功能,但不具有剑道编辑弹出窗口/

    因此,对于那些有相同问题的人,这里有一个解决方案,将其写入javascript,而不是将其添加到 $.validator :

    (function ($, kendo) {
        $.extend(true, kendo.ui.validator, {
            rules: {
                customrequired: function (input) {
                    if (input.is("[data-val-customrequired]")) {
                        return $.trim(input.val()).length > 0;
                    }
                    return true;
                }
            },
            messages: {
                customrequired: function (input) {
                    return input.attr("data-val-customrequired");
                }
            }
        });
    })(jQuery, kendo);