首页 > 解决方案 > 表单提交时的 Blazor EditForm 自定义验证消息

问题描述

我们可以向 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 的内容

标签: c#blazor-server-sideblazor-editform

解决方案


推荐阅读