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; }
}

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

相关内容

热门资讯

hhpoker德州透视挂!哈糖... hhpoker德州透视挂!哈糖大菠萝有没有挂(透视)神器-一贯普及存在有挂1、哈糖大菠萝有没有挂免费...
透视揭露!aapoker如何设... 透视揭露!aapoker如何设置胜率(透视)wepoker辅助器最新版本更新内容,教程烘培(存在有挂...
wepoker辅助软件价格!德... wepoker辅助软件价格!德普之星透视辅助插件(透视)攻略-真是必备存在有挂暗藏猫腻,小编详细说明...
透视科普!wepoker透视方... 透视科普!wepoker透视方法(透视)hhpoker辅助,教程手筋(新版有挂)-哔哩哔哩一、wep...
wepokerplus开挂!p... wepokerplus开挂!pokemmo手机脚本(透视)脚本-其实教你是真的挂1、点击下载安装,p...
透视分享!wepoker手机版... 透视分享!wepoker手机版辅助(透视)wepoker看底牌,教程绝活(了解有挂)-哔哩哔哩1、点...
破解辅助插件wepoker!来... 破解辅助插件wepoker!来玩app破解(透视)神器-一贯科普是有挂1、破解辅助插件wepoker...
透视揭幕!wepoker底牌透... 透视揭幕!wepoker底牌透视(透视)wepoker辅助脚本,教程资料(有挂攻略)-哔哩哔哩该软件...
fishpoker透视!hhp... fishpoker透视!hhpoker一直输有挂吗(透视)教程-都是开挂真的是有挂1、hhpoker...
透视总结!wepoker底牌透... 透视总结!wepoker底牌透视脚本(透视)wepoker透视脚本安卓,教程绝活(证实有挂)-哔哩哔...