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私人局辅助挂,wepoker辅助软件视频(透视)好像存在有挂(哔哩哔哩)1、...
透视举措!wepoker免费脚... 透视举措!wepoker免费脚本咨询,pokemmo修改器手机版(透视)其实是真的挂(哔哩哔哩)1、...
透视方案!wpk作必弊最怕三个... 您好,如何判断wpk辅助软件的真假这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
透视指引!pokerworld... 透视指引!pokerworld辅助器,wepoker透视脚本免费下载(透视)本来有挂(哔哩哔哩)we...
透视机巧!hhpoker透视脚... 透视机巧!hhpoker透视脚本,红龙poker作必弊指令(透视)其实存在有挂(哔哩哔哩)红龙pok...
透视绝活!拱趴大菠萝作必弊方法... 透视绝活!拱趴大菠萝作必弊方法,拱趴大菠萝十三水作必弊(透视)总是是真的透视技巧(哔哩哔哩)1、操作...
透视演示!wpk俱乐部是做什么... 透视演示!wpk俱乐部是做什么的,aapoker如何设置胜率(透视)切实真的有挂(哔哩哔哩)1、wp...
透视演示!aapoker脚本怎... 透视演示!aapoker脚本怎么用,aapoker辅助插件工具(透视)确实是真的脚本挂(哔哩哔哩)一...
透视大纲!pokemmo辅助脚... 透视大纲!pokemmo辅助脚本,aapoker辅助软件合法吗(透视)果然真的是有挂(哔哩哔哩)1、...
透视学习!aapoker万能辅... 透视学习!aapoker万能辅助器,aapoker辅助器是真的吗(透视)切实是有透视器(哔哩哔哩)亲...