繁体   English   中英

Blazor EditForm 表单提交时自定义验证消息

[英]Blazor EditForm custom validation message on form submission

我们可以在 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"); 
            
            
        }
    }

我们在 Blazor 服务器端是否有类似于 ModelState.AddModelError 的东西

您可以添加自定义验证处理程序,如本MS 文档中的示例所示。 首先,不要将 model 传递给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中的事件处理程序,不确定这是否真的有必要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM