How to Preventing Form Submission on Enter Key Press in Blazor
In Blazor, pressing the “Enter” key within a component inside an EditForm will, by default, trigger the form’s submission action. However, Blazor does not natively support e.PreventDefault() or e.StopPropagation() on KeyboardEventArgs. To prevent this default behavior, you can use JavaScript Interop (JS Interop) to handle the keydown event and prevent form submission on “Enter” key press.
In your Blazor component (e.g., Index.razor
), set up the EditForm
as follows:
@inject IJSRuntime JS;
@using System.ComponentModel.DataAnnotations;
<EditForm id="askQuestionForm" Model="@editorModel" OnSubmit="HandleSubmit">
<DataAnnotationsValidator />
<div class="form-group">
<label for="employee-name">Employee Name:</label>
<SfTextBox ID="employee-name" @bind-Value="editorModel.Name"></SfTextBox>
<ValidationMessage For="@(() => editorModel.Name)"></ValidationMessage>
</div>
<SfButton>Submit</SfButton>
</EditForm>
@code {
private EditorModel editorModel = new EditorModel();
public class EditorModel
{
[Required(ErrorMessage = "Enter employee name.")]
[MinLength(3, ErrorMessage = "Name should have more than 2 characters.")]
public string Name { get; set; }
}
private void HandleSubmit()
{
Console.WriteLine("Submit...");
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender) {
JS.InvokeVoidAsync("PreventEnterKey", "askQuestionForm");
}
}
}
In your layout file (e.g., Layout.cshtml
), add the following JavaScript function to prevent the form submission when the “Enter” key is pressed:
<script>
function PreventEnterKey(id) {
var formObj = document.getElementById(id);
formObj.addEventListener('keydown', function (event) {
if (event.key == "Enter") {
event.preventDefault();
return false;
}
});
}
</script>
By following the steps above, you can effectively prevent the form from submitting when the “Enter” key is pressed within an EditForm
in Blazor. This approach utilizes JavaScript Interop to handle the keydown event and prevent the default form submission behavior.