ASPNetCore3.1自定义验证特性&多个特性的组合
创始人
2024-09-20 08:00:49
0

在ASP Net Core 3.1中,可以通过自定义验证特性来对请求的参数进行合法性校验。但是,有时候需要同时对多个参数进行验证,并要求这些验证条件之间都成立才能通过验证。

例如,需要验证一个注册用户提交的表单,要求其中的用户名不能重复,密码必须包含数字和字母,且长度不能小于8个字符。这时候就需要对这三个条件进行组合验证,即只有这三个条件全部成立时,才能通过验证。

以下是实现组合验证的示例代码:

public class CustomValidationAttribute : ValidationAttribute
{
    public string Username { get; set; }
    public bool IncludeDigit { get; set; }
    public bool IncludeLetter { get; set; }
    public int MinLength { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // 验证用户名是否重复,返回错误信息或空
        var dbContext = validationContext.GetService(typeof(AppDbContext)) as AppDbContext;
        if (dbContext.Users.Any(u => u.Username == Username))
        {
            return new ValidationResult($"{Username}已存在。");
        }

        // 验证密码是否包含数字和字母,长度是否>=MinLength
        var password = value?.ToString() ?? "";
        bool hasDigit = IncludeDigit ? password.Any(c => char.IsDigit(c)) : true;
        bool hasLetter = IncludeLetter ? password.Any(c => char.IsLetter(c)) : true;
        bool hasValidLength = password.Length >= MinLength;
        if (!hasDigit || !hasLetter || !hasValidLength)
        {
            return new ValidationResult($"密码不符合要求。");
        }

        // 验证通过
        return ValidationResult.Success;
    }
}

public class RegisterUserModel
{
    [CustomValidation(Username = "admin", IncludeDigit = true, IncludeLetter = true, MinLength = 8)]
    public string Password { get; set; }
}

在上面的代码中,我们定义

相关内容

热门资讯

目前"wepoker... 目前"wepoker黑侠辅助器正版下载"wejoker辅助器要钱玩吗(原来是真的辅助软件)-哔哩哔哩...
透视实锤"sohoo... 透视实锤"sohoo poker辅助器"哈糖大菠萝助手(一贯真的是有辅助插件)-哔哩哔哩哈糖大菠萝助...
透视实锤"来玩app... 透视实锤"来玩app破解"epoker免费透视脚本(本来是真的辅助安装)-哔哩哔哩1、epoker免...
来临"wepoker... 来临"wepoker免费透视"pokermaster破解版(真是真的是有辅助app)-哔哩哔哩1、玩...
现就发布提示"pok... 现就发布提示"pokemmo手机版透视脚本"德州透视hhpoker(确实有辅助app)-哔哩哔哩1、...
透视线上"fishp... 透视线上"fishpoker透视"wepoker免费脚本咨询(原来真的有辅助下载)-哔哩哔哩1.we...
透视规律"hhpok... 透视规律"hhpoker透视工具"aapoker插件(原来存在有辅助辅助器)-哔哩哔哩亲,关键说明,...
现场直击"wepok... 现场直击"wepoker好友助力码"德州局脚本(总是是有辅助app)-哔哩哔哩1)wepoker好友...
透视模拟器"德州hh... 透视模拟器"德州hhpoker脚本"竞技联盟辅助插件(本来有辅助安装)-哔哩哔哩1、竞技联盟辅助插件...
据了解"wpk作必弊... 据了解"wpk作必弊"约局吧能不能开挂(真是是真的辅助工具)-哔哩哔哩1、不需要AI权限,帮助你快速...