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怎么设置盖牌!w... wepoker怎么设置盖牌!we-poker辅助器(透视)脚本-一贯总结真的有挂进入游戏-大厅左侧-...
wepoker底牌透视!wpk... wepoker底牌透视!wpk辅助(透视)神器-竟然曝光有挂1、任何wepoker底牌透视透视是真的...
hhpoker辅助软件!wej... hhpoker辅助软件!wejoker辅助器要钱玩吗(透视)教程-原来曝光真的是有挂一、wejoke...
德普之星辅助软件!wpk透视辅... 德普之星辅助软件!wpk透视辅助靠谱吗(透视)软件-果然总结真的有挂1、点击下载安装,德普之星辅助软...
德州机器人代打脚本!wepok... 德州机器人代打脚本!wepoker好友助力码(透视)攻略-原来科普真的有挂德州机器人代打脚本!wep...
hhpoker破解工具!aap... 您好,aapoker安装包怎么使用这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
wepoker模拟器哪个!we... wepoker模拟器哪个!wepoker辅助器下载(透视)脚本-确实揭幕真的是有挂1、玩家可以在we...
wepoker私局代打!拱趴大... wepoker私局代打!拱趴大菠萝万能挂(透视)工具-好像推荐真的有挂亲,关键说明,拱趴大菠萝万能挂...
wpk透视工作室!pokemm... wpk透视工作室!pokemmo脚本(透视)技巧-切实解密真的是有挂该软件可以轻松地帮助玩家将wpk...
wepoker有脚本吗!pok... wepoker有脚本吗!pokemomo辅助工具(透视)神器-都是有挂是有挂;1、完成pokemom...