【问题标题】:How to access the validation for single field in EditForm?如何访问 EditForm 中单个字段的验证?
【发布时间】:2021-02-23 12:19:09
【问题描述】:

我想根据<EditForm /> 中的验证结果来操作css。

我的简化形式是这样的

<EditForm Model="Registration" OnValidSubmit="Submit">
    <label for="input-username">Username</label>
    <InputText id="input-username" 
               type="text" 
               class="???" 
               @bind-Value="Registration.Username" />
    <p>
        <ValidationMessage For="@(() => Registration.Username)" />
    </p>
</EditForm>

我的表单有比这个更多的字段,所以我只想过滤 Registration.Username 的验证,只编辑 #input-username 的 css 类。

【问题讨论】:

    标签: blazor blazor-client-side blazor-webassembly asp.net-blazor


    【解决方案1】:

    您可以订阅 EditContext 对象的 OnFieldChanged 事件,找出哪个字段发生了变化并采取相应措施。

    <EditForm EditContext="EditContext" OnValidSubmit="Submit">
        <DataAnnotationsValidator />
    
         <label for="input-username">Username</label>
        <InputText id="input-username" type="text" class="MyUsername" 
                   @bind-Value="Registration.Username" />
        <p>
            <ValidationMessage For="@(() => Registration.Username)" />
        </p>
                <button type="submit">Submit</button>
            
    </EditForm>
    
    @code
    {
        private Registration Model = new Registration();
        private EditContext EditContext;
        private string MyUsername = "InitialCssClass";
    
        protected override void OnInitialized()
        {
            EditContext = new EditContext(Model);
    
            EditContext.OnFieldChanged += EditContext_OnFieldChanged;
    
        }
    
        private void EditContext_OnFieldChanged(object sender, 
                                             FieldChangedEventArgs e)
        {
             if (e.FieldIdentifier.FieldName == nameof(Model.Username))
             {
                 MyUsername = "Set here a new class name, etc.";
             }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2017-04-21
      • 2017-12-01
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2020-05-28
      • 1970-01-01
      相关资源
      最近更新 更多