在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

posted @ 2017-05-05 14:04  dudu  阅读(6708)  评论(0编辑  收藏  举报