When the validation fails at the bottom, why the browser shows at the top of the page?
-
19-02-2021 - |
Question
I have just implemented a RequiredFieldValidatior with ValidationSummary by setting a ValidationGroup.
It works fine, when I click the relevant button!
But the viewport changes and shifts at the top of the page and my validaiton result and the button etc stays at the very bottom of the page which is not nice.
Is there a way to prevent this and let the browser still be shopwing the same area after button click?
Additional Note: The validation fails on the client-side; so no post-back occurs. Basically, validation fails, and the viewport slides at the top of the page.
Solution
In your RequiredFieldValidator
there is an option to SetFocusOnError
which will then move the cursor to the Textbox/input type.
Then in your Page declaration at the top of the page, add in MaintainScrollPositionOnPostback="true"
<%@ Page MaintainScrollPositionOnPostback="true" %>
OTHER TIPS
You can achieve this by adding the following directive to the top of your page:
<%@ Page MaintainScrollPositionOnPostback="true" %>
I have done this before to set focus on the fist element that didn't validate when calling validation manually:
//has to be called after Page_ClientValidate()
function ValidatorFocus()
{
var i;
for (i = 0; i < Page_Validators.length; i++)
{
if (!Page_Validators[i].isvalid)
{
document.getElementById(Page_Validators[i].controltovalidate).focus();
break;
}
}
}