Validating and Focusing on Validation - c#

I have a page and in that page i have several user controls, so one of them validates a textbox to see if its empty it works fine... but then i have other controls... and one of them has the submit button, so what i want to do is when the button is clicked if the textbox is empty (and it validates correctly) to jump to that section of the page so that the user can see the error.
Right now it is just showing the message but it is all the way down in the page so the error is there, the user is clicking and clicking but does not know the problem is at the top...
How can I focus on that textbox in that control... when clicking on the submit button which is in another control but they are still both in the same page?
I hope you understand the issue if not please ask and i will be happy to assist with more information.

Here is a way to set focus, put this function in OnClientClick of an ASP.NET button control:
function ValidatorFocus()
{
//force .net validation
Page_ClientValidate();
var i;
for (i = 0; i < Page_Validators.length; i++)
{
if (!Page_Validators[i].isvalid)
{
document.getElementById(Page_Validators[i].controltovalidate).focus();
break;
}
}
}
Manually calling ASP.NET Validation with JavaScript

Are you using the built in ASP.NET validators? If so, you should look into the SetFocusOnError.
<asp:textbox id="txt" runat="server">
<asp:RequiredFieldValidator ID="vld" ControlToValidate="txt" SetFocusOnError="true" />

Related

Asp.net maintainScrollPositionOnPostBack and forms validation fail

I have a very long form that has to be filled out. I have maintainScrollPositionOnPostBack enabled as I have multiple controls that hide/show based on user input.
Since the form is long I'd like for the page to focus and scroll to the first control that caused validation to fail and I have the focus on validation fail option enabled. However, it seems that maintainScrollPositionOnPostBack overrides this (the control does focus but doesn't scroll up to it).
Any ideas for workarounds for this? Everything I've tried so far hasn't worked. It is an asp.net webforms project.
This is a good question and really tricky to get working. But I managed to get one version that you can try and maybe build on.
The MaintainScrollPositionOnPostback="true" -setting sets a series of javascript-events on form submit and window load and these do as you say, "overwrite" the focus set by the validator.
So what I did was add a common css-class to all validators like so:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="error" ErrorMessage="RequiredFieldValidator" SetFocusOnError="true"
EnableClientScript="false" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
And then I added another eventlistener to window.load (note we need to leave also the one that Asp.Net has added so we cannot do windows.load = function...):
<script>
window.addEventListener("load", function () {
var el = document.getElementsByClassName("error");
if (el.length > 0) {
window.location.hash = "#" + el[0].id;
}
});
</script>
Here you might benefit from jQuery use to be able to support more browsers but addEventListener is pretty well supported.
The script searches for the errormessage and focus on that by it's id with anchor. Javascript has focus-method but it's for form elements so that's why this workaround.
Hope this helps!

RequiredFieldValidator error messages displayed after successful Postback and form reset

(Using ASP.NET Web Forms. Microsoft .NET Framework Version:4.0.30319, ASP.NET Version:4.0.30319.34274)
I have an asp:TextBox field with a RequiredFieldValidator for that text field:
<asp:TextBox
runat="server"
ID="MyTextBox" />
<asp:RequiredFieldValidator
runat="server"
ID="RequiredUserName"
ControlToValidate="MyTextBox"
ErrorMessage="MyTextBox is required"
Display="None" />
When the user submits the form on the page, I validate it and then clear the form so that they user can use the form again. The code behind in Page_Load looks like:
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
SaveFormSubmissionToDatabase();
MyTextBox.Text = "";
}
}
So, I validate everything, it Page.IsValid is true, I save the users form data and then try to clear the form for the user to fill in again. But since the form is cleared, the RequiredFieldValid shows its error message, even though I have already run Page.Validate() and have not run it again.
Why is this and what can I do to avoid this error message from being displayed after I clear my form? More generally, why is this RequiredFieldValidator being run again?
I should note that the error message is actually being displayed in an asp:ValidationSummary control.
(I thought that maybe client side validation was triggering the error messages being displayed, so I set EnableClientScript="false" in the RequiredFieldValidator, but that didn't change anything)
I have researched this issue for a bit and have found other people with the same issue, but no solution. This question, for example. The proposed solution there is to redirect to the same page, which doesn't work form my use case because I need to display some information about the form that was just submitted, including a success message, and that information would be lost if I redirected to the same page.
the reason you get the message is because of the call to Page.Validate() which is exactly what is for as the name indicates. And because with every postback the validate is called.
Typically you would not put that code in the Page_Load, but in the submit button's onClick.
i.e.:
protected void SubmitButton_OnClick(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
SaveFormSubmissionToDatabase();
MyTextBox.Text = "";
}
}
Update: Let me refine the reason. In the original post the MyTextBox.Text = "" is not the last thing that happens. The controls on the page will also fire their events and validations, and this happens after the Page_Load event.
For full life-cycle reference: https://msdn.microsoft.com/en-us/library/ms178472.aspx#general_page_lifecycle_stages

Asp Webform Validation One Button multiple groups accordion tabs

I have a webform application that uses asp.net validators. I have a bootstrap accordian (or any accordian jquery etc) and I only want to validate controls that are on the visible panel. I setup a validation group for each panel. I have a single submit button.
I was using jquery to set the validationgroup property, but it seems when done this way, the button ignores the value.
I have tried validating manually but the page seems to skip validation altogether in that case. I am really banging my head against the wall.
<asp:button ID="btnDeleteConfirmation" runat="server" Text="Save" OnClientClick="return Validate();" CausesValidation="False"/>
function Validate() {
var isValid = false;
isValid = Page_ClientValidate(mode);
return isValid;
}
the mode is set when the tab/panel is switched, the value is correct when I check it. The function is called and the return value looks good, but the page postbacks and then i get the following expected error:
Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
How do others handle validation client side when only one tab/panel needs to be validated and there is a single submit button?
Normally in this case I set the validation groups on each section properly, then on whatever button I need to do the validation I do
Page.Validate(groupName);
Then you can call Page.IsValid and it will only use the validated group. That way you don't have to do anything else. Don't associated a validation group for your button either.

How can I make a RequiredFieldValidator trigger a message elsewhere on the page?

I have a page with a repeater containing RadioButtonLists which have requiredFieldValidators attached to them. I need to keep the RFV next to the control (it's the only way I can get it to work to be honest!)
However, the form is made up of a few sections contained in an accordion. This means that when the form is submitted, the item that has failed validation may not be visible, so the user won't know where the error is.
Is there a way I can also have a message by the submit button which is triggered by an RFV changing saying "please go back and check your answers" or something? I guess I'd need to use JQuery / JavaScript as it would be clientside.
There is a special ValidationSummary control for that:
<asp:ValidationSummary ID="Summary" runat="server"
DisplayMode="SingleParagraph"
HeaderText="Please go back and check your answers" />
This control is used to summarize all validation errors on the page.
Try "ValidationSummary". look for example from here.
http://www.w3schools.com/aspnet/control_validationsummary.asp

Submitting a form on a user control by pressing enter on a text field does not work

This seems to be a common problem but I cannot find a solution.
I type in my username and password which are in a login control I have created.
I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event.
If I press the submit button then everything works fine.
using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML.
so you do as Jon said above:
<form runat="server" DefaultButton="SubmitButton">
But ensure you use the Button name that will be rendered.
You can achieve this my making the Button public in your control, or a method that will return it's ClientId.
Let's say your button is called btnSubmit, and your implementation of your control ucLogin.
Give your form an id
<form runat="server" id="form1">
Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id.
protected void Page_Load(object sender, EventArgs e)
{
form1.DefaultButton = ucLogin.btnSubmit.ClientID;
}
If you're using ASP.NET 2.0 or higher, you can set a default button attribute for your page's Form:
<form runat="server" DefaultButton="SubmitButton">
Pressing ENTER on a text input executes Form.onsubmit, not Button.onclick.
I suppose this was inspired by the fact that you can have a form without an actual submit button (depending solely on the use of ENTER).

Categories

Resources