• 在ASP.NET Core中实现自定义验证特性(Custom Validation Attribute)


    这是我们在实际ASP.NET Core项目中用到的,验证用户名中是否包含空格。

    开始是这么实现的(继承ValidationAttribute,重写IsValid方法):

    public class NoSpaceAttribute : ValidationAttribute
    {
        private static readonly Regex _noSpaceRegex = new Regex(@"^[^s]+$", RegexOptions.Compiled);    
    
        public override bool IsValid(object value)
        {
            string stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
    
            if (string.IsNullOrEmpty(stringValue))
            {
                return true;
            }
    
            return _noSpaceRegex.IsMatch(stringValue);
        }        
    }

    但发现这样只对服务端验证有效,对前端验证无效。查资料后知道原来还需要实现 IClientModelValidator 接口(需要安装nuget包——Microsoft.AspNetCore.Mvc.Abstractions):

    public class NoSpaceAttribute : ValidationAttribute, IClientModelValidator
    {
        //...
    
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-nospace", errorMessage);
        }
    
        private bool MergeAttribute(
            IDictionary<string, string> attributes,
            string key,
            string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

    这样依然不够,还需要添加真正干活的前端验证js代码:

    $(function ($) {
        $.validator.addMethod("nospace",
            function (value, element, parameters) {
                return /^[^s]+$/g.test(value);
            });
    
        $.validator.unobtrusive.adapters.addBool("nospace");
    }(jQuery));

    经过这3步,就可以正常进行前后端双重验证。

    【参考资料】 

    Validation using IClientModelValidator

    ASP.Net Core MVC - Client-side validation for custom attribute

  • 相关阅读:
    搭建基本的React Native开发环境
    Java跨平台原理
    MySQL主从复制与Atlas读写分离
    自动生成和安装requirements.txt依赖
    Mac 证书错误
    zabbix报警信息设置
    zabbix自定义监控项数据类型错误
    Centos7.6 双网卡,修改默认路由
    linux 安装 websocketd
    土豆聊天 机器人
  • 原文地址:https://www.cnblogs.com/dudu/p/6812715.html
Copyright © 2020-2023  润新知