How to prevent default enter key behavior on Entry screen in Blazor

In one of my blazor project, there was requirement to prevent default submit behavior on pressing enter key in middle of entry screen. I fixed it like given below.

Any Web browser, if we will press enter key in middle of entry screen and there are any button with type submit then it will triggered it. This is expected behavior of web browser. But we want to disable feature then we do like this.

UI for above screen

@page "/test1"
@using System.ComponentModel.DataAnnotations
<EditForm Model="empModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

   Name: <InputText id="name" @bind-Value="empModel.Name" /> <br /> <br />
   Address: <InputText id="name2" @bind-Value="empModel.Address" /><br /> <br />

    <button type="submit">Submit</button>

@code {
    private Emp empModel = new Emp();

    private void HandleValidSubmit()

    public class Emp
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string? Name { get; set; }

         public string? Address {get; set;}


Step 1: Go to MainLayout.Razor and keep this script file to disable it

<script suppress-error="BL9992">
    //prevent submit on enter
    document.body.addEventListener('keypress', e => {
        if (e.which == 13 && !'button[type=submit]')) {
            const form = e.composedPath().find(e => e.matches('form'))
            const submitButton = form && form.querySelector('button[type=submit]:enabled');
            if (submitButton) {
                const preventSubmit = (e2) => {
                    return false;
                // Browser emulates submit button click, when enter key is pressed, so we need to prevent that.
                form.addEventListener('click', preventSubmit, { once: true, capture: true });
                setTimeout(() => form.removeEventListener('click', preventSubmit, { capture: true }), 0); 
                // better clear the eventlistener despite once:true in case the keypress propagation has been stopped by some other eventhandler

Now it will apply on entire application.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.