Files
qhmes/yy-admin-master/YY.Admin/FluentValidation/SysUserValidator.cs

55 lines
2.1 KiB
C#

using FluentValidation;
using NewLife;
using YY.Admin.Core;
using YY.Admin.Services.Service.User;
namespace YY.Admin.FluentValidation
{
public class SysUserValidator : AbstractValidator<SysUser>
{
private readonly ISysUserService _userService;
public SysUserValidator(ISysUserService userService)
{
_userService = userService;
RuleFor(x => x.Account)
.NotEmpty().WithMessage("账号不能为空")
.Length(4, 20).WithMessage("账号长度需在4~20个字符之间")
.Matches(@"^[a-zA-Z0-9_]+$").WithMessage("账号仅能包含字母、数字和下划线")
.MustAsync(async (user, account, cancellation) =>
{
var exists = await _userService.AccountExistsAsync(account, user.Id);
return !exists;
}).WithMessage("账号已存在");
RuleFor(x => x.RealName)
.NotEmpty().WithMessage("姓名不能为空")
.Length(2, 10).WithMessage("姓名长度需在2~10个字符之间");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("密码不能为空")
.MinimumLength(6).WithMessage("密码长度不能少于6个字符")
.When(x => x.Id == 0);
RuleFor(x => x.NickName)
.Length(2, 10).WithMessage("昵称长度需在2~10个字符之间")
.When(x => !x.NickName.IsNullOrEmpty());
RuleFor(x => x.Sex)
.NotNull().WithMessage("性别不能为空");
RuleFor(x => x.Age)
.NotNull().WithMessage("年龄不能为空")
.GreaterThanOrEqualTo(0).WithMessage("年龄不能小于0")
.LessThanOrEqualTo(150).WithMessage("年龄不能大于150");
//RuleFor(x => x.Birthday)
// .NotNull().WithMessage("出生日期不能为空");
//RuleFor(x => x.Phone)
// .Matches(@"^1[3456789]\d{9}$").WithMessage("手机号码格式不正确!")
// .When(x => !string.IsNullOrWhiteSpace(x.Phone));
}
}
}