Blazor FluentValidation将规则传递给组件



我在Blazor Server中使用FluentValidation,它在独立组件上运行良好,但我想动态地将规则传递给组件。如下所示:

<MyComponent Rules="MyCustomRules">...Text Here...</MyComponent>
@code {
private FluentValidation.AbstractValidator<MyComponent> MyCustomRules()
{
RuleFor(field => field._value)
.NotEmpty().WithMessage(field => $"{field.Name} cannot be empty");
}
}

MyComponent中的Rules参数可以将动态Rules应用于MyComponent。这可能吗?如何?

多亏了下面的建议和一些进一步的研究,我终于明白了。正如@Michal Diviš所指出的,我只是将AbstractValidator作为Rules参数传递给组件。

MyComponent代码背后:

[Parameter]
public AbstractValidator<TextField> Rules { get; set; }

然后,在使用组件的页面中,我创建规则并将其传递给组件<MyComponent Rules="MyRules"

Validation MyRules= new Validation();
private class Validation : AbstractValidator<TextField>
{
public Validation()
{
RuleFor(field => field._value)
.NotEmpty().WithMessage("Field cannot be empty");
}
}

最新更新