Blazor WASM -流畅验证



在我的自定义验证器中创建了以下规则:

public class AddInvoiceParameterCommandValidator : AbstractValidator<AddInvoiceParameterCommand>
{
public AddInvoiceParameterCommandValidator(IStringLocalizer<AddInvoiceParameterCommandValidator> localizer)
{
RuleFor(p => p.Start)
.Must(x => x > 0)
.WithMessage(x => localizer["Start must be greater than 0!"]);
RuleFor(p => p.Prefix)
.Must(x => !string.IsNullOrWhiteSpace(x))
.WithMessage(x => localizer["Prefix is required!"])
.MaximumLength(5)
.WithMessage(x => localizer["Length must not exceed"] + " 5 characters");
RuleFor(p => p.End)
.Must(x => x > 0)
.WithMessage(x => localizer["End must be greater than 0!"]);
RuleFor(x => x)
.Must(StartMustBeLessThanEnd)
.WithMessage(localizer["Start must be less than end!"]);
}
private bool StartMustBeLessThanEnd(AddInvoiceParameterCommand parameter)
{
return parameter.Start < parameter.End;
}
}

对于Start和End没有问题,因为当它们不大于0时,我在前端表单中获得消息。问题是,如何在前端显示消息,因为"开始"必须小于"结束"。规则吗?

这是我目前使用的模态代码:(Blazor WASM + MudBlazor)

@inject Microsoft.Extensions.Localization.IStringLocalizer<AddInvoiceParameterModal> _localizer

<EditForm Model="@AddInvoiceParameterModel" OnValidSubmit="SaveAsync">
<FluentValidationValidator @ref="_fluentValidationValidator" />
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-3 mb-n1" />
@_localizer["Add Parameter"]
</MudText>
</TitleContent>
<DialogContent>
<MudGrid>
<MudItem xs="12" md="6">
<MudTextField T="int" For="@(() => AddInvoiceParameterModel.Start)" @bind-Value="AddInvoiceParameterModel.Start" Label="@_localizer["Start"]" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="int" For="@(() => AddInvoiceParameterModel.End)" @bind-Value="AddInvoiceParameterModel.End" Label="@_localizer["End"]" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" For="@(() => AddInvoiceParameterModel.Prefix)" @bind-Value="AddInvoiceParameterModel.Prefix" Label="@_localizer["Prefix"]" />
</MudItem>
</MudGrid>
</DialogContent>
<DialogActions>
<MudButton DisableElevation Variant="Variant.Filled" OnClick="Cancel">@_localizer["Cancel"]</MudButton>
<MudButton DisableElevation Variant="Variant.Filled" ButtonType="ButtonType.Submit" Disabled="@(!Validated)" Color="Color.Success">@_localizer["Save"]</MudButton>
</DialogActions>
</MudDialog>
</EditForm>

您可以这样做来显示带有start:

的消息
RuleFor(p => p.Start)
.Must(x => x > 0).WithMessage(x => localizer["Start must be greater than 0!"])
.Must(StartMustBeLessThanEnd).WithMessage(localizer["Start must be less than end!"]);

或者您可以添加一个汇总控件,显示与属性无关的消息:

<EditForm Model="@AddInvoiceParameterModel" OnValidSubmit="SaveAsync">
<FluentValidationValidator @ref="_fluentValidationValidator" />
[put this where you want displayed ]
<Microsoft.AspNetCore.Components.Forms.ValidationSummary />

相关内容

  • 没有找到相关文章

最新更新