4
votes

Having a Blazor EditForm and a contained InputTextArea (i.e. a multiline text box), I do want to validate and submit the form, when the user presses Ctrl+Enter, just as if he would click the submit button.

I've successfully got the keyboard handler connected like this:

<EditForm Model="@myModel" Format="g" OnValidSubmit="@Store" @ref="_editForm">
    <InputTextArea 
        onkeypress="@(async e => await myKeyPress(e))"
        @bind-Value="myModel.Foo" />
    <button type="submit">Store it</button>
</EditForm>

With this code behind:

private EditForm _editForm;

private async Task myKeyPress(KeyboardEventArgs key)
{
    if (key.CtrlKey && key.Code == @"Enter")
    {
        _editForm.??? // What to call here?
    }
}

Unfortunately, I see no method in the EditForm class that I could call to submit and validate the form, as if the user would click the submit button.

I've looked at this and this SO question with no success.

My question

How to programmatically submit and validate a Blazor form?

1
But suppose that the user has only pressed Enter after typing. This will also submit the form... Actually, the form always submits if an input control has the focus, and you hit enter. Think about that, and reformulate your question...enet
@enet Since it is an InputTextArea which ist a multiline control, pressing the Enter key simply puts the keyboard caret into the next line.Uwe Keim
Yes, you're right. I did not put attention to this fact.enet

1 Answers

3
votes
<EditForm Context=MyCurrentEditContext>
  <InputTextArea 
        onkeypress="@(async e => await myKeyPress(MyCurrentEditContext, e))"
        @bind-Value="myModel.Foo" />
    <button type="submit">Store it</button>
</EditForm>

@code
{
private async Task myKeyPress(EditContext editContext, KeyboardEventArgs key)
{
    if (key.CtrlKey && key.Code == @"Enter")
    {
        if (editContext.Validate())
        {
          ... Do stuff if valid
        }
    }
}
}