您好,欢迎来到叨叨游戏网。
搜索
您的当前位置:首页在ASP.NET Core中实现自定义验证特性(Custom Validation Attribute)

在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步,就可以正常进行前后端双重验证。

【参考资料】 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务