Files
Atomx/Atomx.Admin/Atomx.Admin.Client/Validators/LoginModelValidator.cs
2025-12-09 17:39:21 +08:00

45 lines
1.9 KiB
C#

using Atomx.Admin.Client.Models;
using FluentValidation;
using Microsoft.Extensions.Localization;
namespace Atomx.Admin.Client.Validators
{
public class LoginModelValidator : AbstractValidator<LoginModel>
{
public LoginModelValidator(IStringLocalizer<LoginModelValidator> 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<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(ValidationContext<LoginModel>.CreateWithOptions((LoginModel)model, x => { x.IncludeProperties(propertyName); }));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
}