Search code examples
c#eventsblazor-server-sideblazor-editform

How can I detect a change in a Blazor Server EditForm before the form is submitted


Essentially, what I'm trying to do, is have the 'Update' button within an EditForm appear disabled, until the user has made a change to the text contained within a textbox.

<EditForm EditContext="@EditContext">
    <InputText @bind-Value="SomeModel.Text></InputText>
    ...
<EditForm/>

I've set up the event handler as follows

private EditContext EditContext { get; set; }
protected override void OnInitialized()
{
    this.EditContext = new EditContext(this.SomeModel);
    EditContext.OnFieldChanged += FieldChanged;
}

This works, but not in the way I want it to. With this I have to wait until the user changes focus before the event fires, but I want it to fire as soon as the text changes (The equivalent of WinForms TextBox.OnTextChanged)


Solution

  • 3rd party libraries usually have this implemented in their textbox controls but since you're using the existing Blazor InputText control, Microsoft shared a way to use oninput with InputText by making your own custom Text control as shown here.

    Use the InputText component to create a custom component that uses the oninput event (input) instead of the onchange event (change). Use of the input event triggers field validation on each keystroke