我们可以在Blazor中添加自定义验证消息到EditForm吗?我的表单如下所示,在提交表单时,我必须执行一些业务逻辑检查,以查看参数提供的值是否OK,如果不OK,我必须显示自定义动态验证消息
<EditForm Model="@starship" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label>
Identifier:
<InputText @bind-Value="starship.Identifier" />
</label>
</p>
<p>
<label>
Description (optional):
<InputTextArea @bind-Value="starship.Description" />
</label>
</p>
<p>
<label>
Maximum Accommodation:
<InputNumber @bind-Value="starship.MaximumAccommodation" />
</label>
</p>
<p>
<label>
Engineering Approval:
<InputCheckbox @bind-Value="starship.IsValidatedDesign" />
</label>
</p>
<p>
<label>
Production Date:
<InputDate @bind-Value="starship.ProductionDate" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>
@code {
private Starship starship = new() { ProductionDate = DateTime.UtcNow };
private void HandleValidSubmit()
{
Logger.LogInformation("HandleValidSubmit called");
//I have to check for some custom validation spefic to this form and end result is
//i might have to show a validation message against the property ProductionDate
// Please choose a date before 01/01/2021 or something similar
Does Blazor does have anything like
ModelState.AddModelError("Key","Error message");
}
}
我们有类似ModelState的东西吗?Blazor服务器端AddModelError
您可以添加自定义验证处理程序,如本MS文档中的示例所示。首先,不要将您的模型传递给EditForm
,而是传递给EditContext
,它可以让您访问一些生命周期方法。以下是相关代码:
OnParametersSetAsync
:
// Create EditContext
editContext = new EditContext(assignment);
// Create additional message store for the custom validation messages
validationMessageStore = new(editContext);
// Add additional validation handler
editContext.OnValidationRequested += OnValidationRequestedAsync;
以下是自定义验证处理程序的代码:
private async void OnValidationRequestedAsync(object sender, ValidationRequestedEventArgs e)
{
// clear previous error messages
validationMessageStore.Clear();
// check DB if Title already exists
bool exists = await myService.IsPresent(myModel.Title);
// While waiting for this async process, OnValidSubmit gets called
if (exists)
{
// yes, so add a validation message
validationMessageStore.Add(() => myModel.Title, "The Title is already used.");
// inform ValidationSummary that a new error message has been added
editContext.NotifyValidationStateChanged();
}
}
如问题#72827137所述,似乎也有必要在OnValidSubmit
中执行检查:
// check DB if Title already exists
bool exists = await myService.IsPresent(myModel.Title);
if (exists)
{
// do nothing if invalid (error message is displayed by OnValidationRequestedAsync)
return;
}
// ...
上面链接中的示例还取消了Dispose
中的事件处理程序,不确定这是否真的有必要。