如何访问EditForm中单个字段的验证?

时间:2020-11-11 14:01:43

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

我想根据<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类。

1 个答案:

答案 0 :(得分:2)

您可以订阅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.";
         }
    }
}