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透视方法,微乐自建房脚本使用安全吗,了解脚本(有挂总结)-哔哩哔哩wepok...
脚本透视!hhpkoer辅助挂... 脚本透视!hhpkoer辅助挂是真的吗,hhpoker有后台操作吗(透视)确实真的是有挂(哔哩哔哩)...
据玩家消息!wepoker软件... 据玩家消息!wepoker软件安装包,微乐自建房辅助神器怎么安装,教你脚本(确实有挂)-哔哩哔哩1、...
透视攻略!德州局HHpoker... 透视攻略!德州局HHpoker透视脚本,微乐小程序辅助开发透视,有挂脚本(有挂技巧)-哔哩哔哩1、德...
透视开挂!hhpoker辅助,... 透视开挂!hhpoker辅助,hh poker辅助器先试用(透视)其实是真的软件(哔哩哔哩)暗藏猫腻...
透视分享!aapoker辅助器... 透视分享!aapoker辅助器是真的吗,aapoker怎么开辅助器(透视)好像存在有挂(哔哩哔哩)1...
值得注意的是!线上德州的辅助器... 值得注意的是!线上德州的辅助器是什么,广西微乐小程序微信辅助器免费,详情透视(有挂方针)-哔哩哔哩1...
透视了解!aapoker如何设... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视攻略!hhpoker软件安... 透视攻略!hhpoker软件安装包,微乐小游戏万能修改器,详情透视(有挂秘诀)-哔哩哔哩亲,关键说明...
透视专业!wpk透视辅助下载,... 透视专业!wpk透视辅助下载,wpk模拟器是什么(透视)好像是真的工具(哔哩哔哩)脚本下载中分为三种...