33 lines
1.2 KiB
C#
33 lines
1.2 KiB
C#
using Atomx.Admin.Client.Models;
|
|
using FluentValidation;
|
|
using Microsoft.Extensions.Localization;
|
|
|
|
namespace Atomx.Admin.Client.Validators
|
|
{
|
|
public class CategoryModelValidator : AbstractValidator<CategoryModel>
|
|
{
|
|
public CategoryModelValidator(IStringLocalizer<CategoryModelValidator> localizer)
|
|
{
|
|
RuleFor(p => p.Name).NotEmpty().WithMessage("名称不能为空");
|
|
RuleFor(p => p.ParentId).Must((p,id)=> ValidateParent(id,p)).WithMessage("不能选择自己做上级分类");
|
|
}
|
|
|
|
private bool ValidateParent(long parentId, CategoryModel model)
|
|
{
|
|
if (model.Id == parentId && model.Id > 0)
|
|
{
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
|
|
{
|
|
var result = await ValidateAsync(ValidationContext<CategoryModel>.CreateWithOptions((CategoryModel)model, x => { x.IncludeProperties(propertyName); }));
|
|
if (result.IsValid)
|
|
return Array.Empty<string>();
|
|
return result.Errors.Select(e => e.ErrorMessage);
|
|
};
|
|
}
|
|
}
|