我们可以在Blazor中向EditForm添加自定义验证消息吗?我的表单如下所示,在提交表单时,我必须执行一些业务逻辑检查,以查看为参数提供的值是否确定,如果不是确定,则必须显示自定义动态验证消息。
<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.AddModelError的东西吗?
发布于 2022-07-01 09:34:28
可以添加自定义验证处理程序,如本达克中的示例所示。首先,不要将您的模型传递给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中的事件处理程序取消挂钩,不确定这是否真的有必要。
https://stackoverflow.com/questions/69724492
复制相似问题