IAM使用流畅的验证和使用MediatR库的CQRS.我的解决方案中使用了以下Fluent包版本以及.NET 7和C#.
FluentValidation-11.8.1
FluentValidation.DependencyInjectionExtensions-11.8.1
我有以下针对"Group"属性的验证器,该属性是CreateGroupRequest
和UpdateGroupRequest
中的"字符串"数据类型.
public class CreateGroupRequest : IRequest<BaseResponse<CreateGroupResponse>>
{
public string Group { get; set; }
}
public class CreateGroupValidator : AbstractValidator<CreateGroupRequest>
{
public CreateGroupValidator(IOptions<FeatureOptions> options)
{
var featureOptions = options.Value;
ClassLevelCascadeMode = CascadeMode.Stop;
RuleFor(r => r.Group).NotNull().WithMessage("Group can't be null.");
RuleFor(r => r.Group).NotEmpty().WithMessage("Group must not be empty.");
RuleFor(r => r.Group).Length(featureOptions.GroupMinLength, featureOptions.GroupMaxLength)
.WithMessage("Group length must be between 1 and 15.");
RuleFor(r => r.Group).Matches(featureOptions.GroupAllowedCharactersRegex)
.WithMessage("Group must start and end with lower case letters or numbers. It may contain \"_\" and \" - \".");
}
}
public class UpdateGroupValidator : AbstractValidator<UpdateGroupRequest>
{
public UpdateGroupValidator(IOptions<FeatureOptions> options)
{
var featureOptions = options.Value;
ClassLevelCascadeMode = CascadeMode.Stop;
RuleFor(r => r.Group).NotNull().WithMessage("Group can't be null.");
RuleFor(r => r.Group).NotEmpty().WithMessage("Group must not be empty.");
RuleFor(r => r.Group).Length(featureOptions.GroupMinLength, featureOptions .GroupMaxLength)
.WithMessage("Group length must be between 1 and 15.");
RuleFor(r => r.Group).Matches(labelingOptions.GroupAllowedCharactersRegex)
.WithMessage("Group must start and end with lower case letters or numbers. It may contain \"_\" and \" - \".");
}
}
我在验证器中使用ClassLevelCascadeMode = CascadeMode.Stop
设置.
还有其他请求需要验证"Group"属性.有没有办法移动"Group"属性上的所有验证,以便在单个位置定义规则并在验证器中重用?
在这方面的任何帮助都是非常感谢的.