ASP.NETCore5.0MVC中的自定义字段验证错误
创始人
2024-09-17 11:00:56
0

在ASP.NET Core MVC中,可以通过自定义属性来添加字段验证规则。然而,在使用自定义属性时,可能会遇到一些验证错误。解决这些错误的一种方法是使用自定义模型验证器。

以下示例演示了如何使用自定义模型验证器处理身份证号字段的验证:

  1. 创建自定义属性
public class IdentityCardAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //验证规则
        if (value == null)
        {
            return ValidationResult.Success;
        }

        string identityCard = value.ToString();

        //身份证正则表达式
        const string regexPattern = @"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)";
        bool isValid = Regex.IsMatch(identityCard, regexPattern);

        if (!isValid)
        {
            return new ValidationResult("身份证号格式不正确");
        }

        return ValidationResult.Success;
    }
}
  1. 在要验证的类中使用自定义属性
public class Person
{
    [Required(ErrorMessage ="姓名不能为空")]
    public string Name { get; set; }

    [IdentityCard(ErrorMessage ="身份证号格式不正确")]
    public string IdentityCard { get; set; }
}
  1. 创建自定义模型验证器
public class IdentityCardValidator : IObjectModelValidator
{
    public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
    {
        if (model == null)
        {
            return;
        }

        var properties = model.GetType().GetProperties();
        var messages = new List();

        foreach (var property in properties)
        {
            var value = property.GetValue(model);

            var attributes = property.GetCustomAttributes();
            foreach (var attribute in attributes)
            {
                if (attribute.GetType() == typeof(IdentityCardAttribute))
                {
                    var result = ((IdentityCardAttribute)attribute).GetValidationResult(value, new ValidationContext(model));
                    if (result != ValidationResult.Success)
                    {
                        messages.Add(result);
                    }
                }
            }
        }

        if (messages.Count > 0)
        {
            validationState[model] = new ValidationStateEntry()
            {
                SuppressValidation = false,
                ValidationState = ModelValidationState.Invalid,
            };

            foreach (var message in messages)
            {
                actionContext.ModelState.AddModelError("IdentityCard", message.ErrorMessage);
            }
        }
    }
}
  1. 注册自定义模型验证器

在Startup.cs文件的ConfigureServices方法中注册自定义模型验证

相关内容

热门资讯

透视免费!wepoker公共底... 透视免费!wepoker公共底牌(透视)钱塘十三水其实真的有挂(竟然是真的辅助神器)-哔哩哔哩1、钱...
经调查!wepoker游戏下载... 经调查!wepoker游戏下载(透视)免费广东雀神智能插件安装(果然真的有辅助插件)-哔哩哔哩1、操...
昨日!wpk作必弊是真的吗(透... 昨日!wpk作必弊是真的吗(透视)上饶打炸攻略(切实是真的辅助下载)-哔哩哔哩1、这是跨平台的上饶打...
辅助透视!智星菠萝可以辅助吗(... 辅助透视!智星菠萝可以辅助吗(透视)九九联盟后台可以操作吗(本来存在有辅助工具)-哔哩哔哩1、首先打...
透视游戏!扑克之星辅助(透视)... 透视游戏!扑克之星辅助(透视)微信十三张脚本(一直是有辅助修改器)-哔哩哔哩微信十三张脚本辅助器是一...
据目击者称!wpk私人辅助(透... 据目击者称!wpk私人辅助(透视)闲逸游戏游透视吗(真是是有辅助安装)-哔哩哔哩进入游戏-大厅左侧-...
透视透视!wepokerplu... 透视透视!wepokerplus脚本(透视)中至九江都昌讨赏插件(确实是有辅助工具)-哔哩哔哩1、每...
此事备受玩家关注!aa pok... 此事备受玩家关注!aa poker透视软件(透视)创思维辅助软件(竟然真的是有辅助app)-哔哩哔哩...
此事引发网友热议!wepoke... 此事引发网友热议!wepoker分析(透视)皮皮衡阳字牌黑科技视频(竟然真的是有辅助神器)-哔哩哔哩...
在玩家背景下!hhpkoer辅... 在玩家背景下!hhpkoer辅助器(透视)衢州都莱辅助器是真的假的(果然是真的辅助下载)-哔哩哔哩1...