简体   繁体   English

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

[英]Blazor EditForm custom validation message on form submission

Can we add a custom validation message to an EditForm in Blazor?我们可以在 Blazor 中的 EditForm 中添加自定义验证消息吗? My form is like below and on submission of form i have to perform some business logic checks to see the provided value for a parameter is OK or not and if its not OK i have to show a custom dynamic validation message我的表单如下所示,在提交表单时,我必须执行一些业务逻辑检查以查看为参数提供的值是否正常,如果不正常,我必须显示自定义动态验证消息

 <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"); 
            
            
        }
    }

Do we have something similar to ModelState.AddModelError in Blazor server side我们在 Blazor 服务器端是否有类似于 ModelState.AddModelError 的东西

You can add a custom validation handler as shown in the example in this MS doc .您可以添加自定义验证处理程序,如本MS 文档中的示例所示。 First, don't pass your model to the EditForm but an EditContext which gives you access to some life cycle methods.首先,不要将 model 传递给EditForm ,而是传递给EditContext ,它可以让您访问一些生命周期方法。 Here is the relevant code:以下是相关代码:

OnParametersSetAsync : 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;

Here is the code for the custom validation handler:这是自定义验证处理程序的代码:

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();
    }
}

As descibed in question #72827137 , it seems necessary to perform the check also in OnValidSubmit :如问题#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;
}

// ...

The example in the above link also un-hooks the event handler in Dispose , not sure if this is really necessary.上面链接中的示例还取消了Dispose中的事件处理程序,不确定这是否真的有必要。

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

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