Blazor: How to scroll to first error in edit form?

1.5k Views Asked by At

I have an editform with a large number of fields. If the user makes an error and attempts to submit the form, they must scroll manually to see the errors. With javascript, something like this could be done:

var element = document.getElementById("content");
element.scrollIntoView();

In blazor, I can use JS if I must but I don't necessarily have an ID to scroll to.

Is there a good way of scrolling to the first error in an editform on submit?

1

There are 1 best solutions below

1
Dave On

Here's how I accomplished it. I'm using OnInvalidSubmit on the EditForm. My ValidationMessage control adds the class 'validation-message' so I'm scrolling to the parent element of the first error message found, you may want to go an extra node up depending on your HTML.

I created a class for my Blazor page to inherit from

public class FormBase : ComponentBase
{
    [Inject]
    protected IJSRuntime JSRuntime { get; set; } = null!;

    internal async Task HandleInvalidSubmit()
    {
        await JSRuntime.InvokeVoidAsync("scrollToFirstError");
    }
}

Then inherit that in the razor page and add the OnInvalidSubmit to EditForm

@inherits FormBase

<EditForm EditContext="editContext" OnInvalidSubmit="@HandleInvalidSubmit">

My JavaScript is as follows. I added a 500ms delay so the page has time to add the error messages before getElementsByClassName is called

function scrollToFirstError() {

    delay(500).then(() => {

        var element = document.getElementsByClassName("validation-message")[0];
        if (element != null) {
            element.parentNode.scrollIntoView();
        }

    });
}

function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}