using Atomx.Admin.Client.Models; using FluentValidation; using Microsoft.Extensions.Localization; namespace Atomx.Admin.Client.Validators { public class LoginModelValidator : AbstractValidator { public LoginModelValidator(IStringLocalizer localizer) { // helper funcs to get localized text or fallback string AccountEmpty() => localizer?["Login.Account.Empty"].Value ?? "登录账号不能为空"; string AccountLength() => localizer?["Login.Account.Length"].Value ?? "用户名长度必须再2-100个字符之间"; string PasswordEmpty() => localizer?["Login.Password.Empty"].Value ?? "请输入登录密码"; string PasswordLength() => localizer?["Login.Password.Length"].Value ?? "登录密码必须在6-32位长度之间"; RuleFor(p => p.Account) .NotEmpty() .WithMessage(_ => AccountEmpty()); RuleFor(p => p.Account) .Length(2, 100) .When(p => !string.IsNullOrEmpty(p.Account)) .WithMessage(_ => AccountLength()); RuleFor(p => p.Password) .NotEmpty() .WithMessage(_ => PasswordEmpty()); RuleFor(p => p.Password) .Length(6, 32) .When(p => !string.IsNullOrEmpty(p.Password)) .WithMessage(_ => PasswordLength()); } public Func>> ValidateValue => async (model, propertyName) => { var result = await ValidateAsync(ValidationContext.CreateWithOptions((LoginModel)model, x => { x.IncludeProperties(propertyName); })); if (result.IsValid) return Array.Empty(); return result.Errors.Select(e => e.ErrorMessage); }; } }