RequiredFieldValidator have to click twice - asp.net

I have run into the same problem as described here.
Only the question is marked as answered with only an explanation as to why you may have to click twice when using a RequiredFieldValidator on input fields - once as the blur of a textbox(for example) will correct the validation and then again to actually post the form.
I don't want to have to click a button twice! Does anyone know a solution or workaround to this?

You could add EnableClientScript=false to the validator.
That prevents the client-side validation, so you will always get a postback (which may not exactly be what you want, though). The validation will still be done, just server-side.
Be sure to wrap the button-click logic in a if (Page.IsValid) { ... }, to check the status of the validators.

Apologies for not posting code previously I assumed this to be a standard problem with the RequiredFieldValidator, but have since realised my particular problem was coming from a CompareValidator, used to ensure entered passwords matched.
The CompareValidator was causing the issue that I described, causing me to have to click away from the field to blur and validate, before being able to click on the post button.
I'm not sure why but changing the Display of the CompareValidator from Dynamic to Static has cleared the problem up.

If the validator is Display="Dynamic", and the appearance of the error message causes the submit button to move, then the MouseUp event is not received by the submit button. In this case, the validation fires and clears the error message, but the submit button does not fire. To solve the problem, either set the the validators to be Display="Static", or rearrange the form so that the submit button does not move when error messages appear.
Here's a way to reserve about one, vertical line of space for a dynamic validation message:
<div style="height:1.5em;overflow:visible;">
<asp:RequiredFieldValidator ID="R1" runat="server"
ErrorMessage="Name is required" ControlToValidate="TextBoxName"
Display="Dynamic"></asp:RequiredFieldValidator>
</div>
I did not find it necessary to set EnableClientScript="false", although that did help for a CustomValidator that had no client-side validation function implemented.

Posting your code is always a good idea, That way we could run your code in a test environment and modify it to ensure it works before posting our answer.
I would suggest adding
causesValidation="true"
to your button to see if that works.

I have a better idea.
Add Text="" to textbox Control.
Add InitialValue="" to Validator Control.
What it will do, when it will be posting, it will find the value of the text box is still the initail value and it will throw an error and the form will not be posted.
Try this:
<asp:RequiredFieldValidator ID="reqFieldCloseComment" ControlToValidate="tbCloseComment" ValidationGroup="ChangeStatus" ErrorMessage="Please enter a reason" Display="Dynamic" runat="server" InitialValue=""></asp:RequiredFieldValidator>
<asp:TextBox ID="tbCloseComment" runat="server" CausesValidation="true" TextMode="MultiLine" Height="107px" Width="400px" Text=""></asp:TextBox>
<asp:Button ID="btnCloseRequestFinal" Text="Finish" CssClass="CloseReqButton" runat="server" ValidationGroup="ChangeStatus" />

Here is code that is working fine for me and helping to get rid of double click.
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"
Enabled="true" MaxLength="20" onfocus="SetActiveControl(this);" Text=""
CausesValidation="true" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" Display="Static" ErrorMessage="Ha!" SetFocusOnError="True" EnableClientScript="true" ForeColor="" InitialValue="" />

$(function() {
$("input.btn").on("click",function(){
if(Page_BlockSubmit == true) {Page_BlockSubmit = false};
})
});
Page_BlockSubmit is a JS variable defined by the js generated from code behind when you define the validator . I haven't went deeper to know why MS need this variable, but the scenario is:
the first click will make Page_BlockSubmit become false.
the second click will check the value of Page_BlockSubmit and return true.
if you implemented the code I posted, every time you click the button, the variable will be set as false which will trigger the submit at every click.
And, you can use google chrome to trace the value of Page_BlockSubmit.

Related

ASP.Net textbox OnTextChanged firing even though validation is invalid

Here's a simple version of my code:
<asp:TextBox ID="textBox" runat="server" AutoPostBack="true" OnTextChanged="textChanged" CausesValidation="true" ValidationGroup="valGroup"></asp:TextBox>
<asp:RegularExpressionValidator ID="regEx" runat="server" ControlToValidate="textBox" ValidationGroup="valGroup" ErrorMessage="Not a valid number." Display="Dynamic" ValidationExpression="(^0*[1-9]+\d*(\.\d+)?$)|(^0*\.0*[1-9]+\d*$)" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSaveClick" ValidationGroup="valGroup" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancelClick" CausesValidation="false" />
It's a text box with a regular expression validator that's supposed to restrict the input to be only positive real numbers. When the text changes and it passes validation a textChanged() function is called.
If the text is invalid, textChanged() won't fire, and the save button won't work as well.
This works as intended.
I've also got a cancel button, and it's supposed to just clear the text box (and some other things server side). It should be able post back to the server whether or not the text box is valid, hence the CausesValidation="false" tag.
My problem is that when I enter something invalid into the text box, and then click cancel it actually executes textChanged() before btnCancelClick(). Even though it isn't valid.
This is a huge problem because textChanged() uses the text box text as a number, so the page throws an exception.
I have no idea what's causing textChanged() to be called. For one thing, the cancel button doesn't even call that function. And the regular expression validator should prevent the text box from calling it.
Edit: I've tried making some changes and experimenting.
function cancel()
{
document.getElementById('<%=textBox.ClientID%>').value = "";
}
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="cancel()" CausesValidation="false" />
I switched the cancel button to call a JavaScript method to try to clear the text box. The results are kind of interesting.
When an invalid string is entered as the first thing, then the cancel button works fine. It clears the text box without textChanged() being called.
If I type in a valid number, textChanged() is called as I expect. But when I click the cancel button it does call cancel(), and immediately after that it calls textChanged() again, but now the text box is empty, leading to an exception.
A similar thing happens if I enter something valid, and then make it invalid. textChanged() is called for the valid input. When the incorrect input is added, the validator prevents textChanged() from being called. But when I click cancel it goes from cancel() to textChanged().
I was thinking that maybe it was because validators don't persist through postback, but with the JavaScript function cancel() the button can't cause the page to postback. textChanged() has to be what's causing it, but I have no idea how.
Edit 2: I'm not going to mark this solved, since it's still a huge problem in my opinion, but I have found a workaround.
<script>
function cancel() {
document.getElementById('<%=textBox.ClientID%>').value = "";
return false;
}
</script>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="return cancel();" CausesValidation="false" />
This doesn't allow the button to cause a postback under any circumstances. It's fixing something that shouldn't be there in the first place, but there it is.
This helps with the button click, but not with other things. I've got a GridView with an OnSelectedIndexChanged function server-side. It also causes the page to post back with the textChanged() function. I could try to create a JavaScript version of the GridView function and fix it like the cancel button, but at this stage I'll probably remove the OnTextChanged event handler and put the textChanged() function and put it behind a button.
add causesvalidation="true" works for me on the textbox control.
So close... What's needed is simply setting a dedicated name to the ValidationGroup name on the Cancel button. This will cause it to be processed out of cycle with the rest of the validation. Not setting it effectively puts it in the "default" validation group which behaves (as you've seen), a bit oddly.
To allow the Cancel button to be exempt from the rest of the form validation, the rule I generally apply is [ValidationGroupName]Cancel to ensure it's triggered outside that block of validation. In this case, setting the Cancel button to something like;
<asp:Button ID="btnCancel" runat="server" Text="Cancel" ValidationGroup="valGroupCancel" OnClick="btnCancelClick" />
Should give you your expected behaviour.

RequiredFieldValidator Control displays the Error Text on Page_Load

I am having trouble with the <asp:RequiredFieldValidator> in this code.
<asp:Label ID="email_Label" runat="server" Text="Email"></asp:Label>
<asp:TextBox ID="email_Text" runat="server" MaxLength="40" Width="250"></asp:TextBox> *
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="email_Text" Text="Required"></asp:RequiredFieldValidator>
According to the W3schools documentation here I have used the <asp:RequiredFieldValidator> correctly, however instead of displaying the label and text box the page also displays the error message. This happens on page_load so the value has not had a chance to change from the default yet. I want the error text to display after the user clicks the Save button at the bottom of the form I am building.
What is Being Displayed:
Email[TextBox] * Required
What Should Be displayed:
Email[TextBox] *
Am I missing a parent element for the validator or something. According to the example on w3schools site no parent element should be needed. In fact the way they have their example set-up is exactly what I was expecting for this.
Use Validation Group if want to display Error message on Button click. Like this.
<asp:RequiredFieldValidator ID="rqtxtQName" ValidationGroup="save" ControlToValidate="txtQueueName" runat="server" ErrorMessage="Some required field are missing." SetFocusOnError="True"Display="Dynamic"></asp:RequiredFieldValidator>
and use validation group on Button also.
<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="save" OnClick="btnSubmit_Click"/>
Hope it will helps.
you should use ErrorMessage instead of Text
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="email_Text" ErrorMessage="Required"></asp:RequiredFieldValidator>
If you want to validation on save button click event then set property ValidationGroup="Group1"
for RequiredFieldValidator and also for save button. So it will check validation when you click save button.
And For display message you can use ErrorMessage property.
Thanks,
Hitesh
Set the RequiredFieldValidator this way. Remove the property: 'TextRequired' & put a * inbetween the opening and closing tag.
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="email_Text">*</asp:RequiredFieldValidator>
Also, Do not set the ErrorMessage property as this will again not fit your requirements.

Why does a failed validation prevent postbacks from control in other validation groups?

I have an asp.net web form with several textboxes, buttons, and other controls. One of the buttons is supposed to trigger validation of content in some of the textboxes. This works fine, except that if validation fails, all subsequent postbacks of the page are prevented. Fixing the invalid values gets rid of the error messages, but postback still does not occur.
The validation is occurring within an AJAX UpdatePanel. I'm not sure if that matters or not.
I'm glad the workaround is fine for you, but for the benefit of others who land this page, disabling client side validation is far from an acceptable solution. So here goes:
Why it happened only when UpdatePanel was around, is still unclear to me, however:
As others have mentioned, the issue you were having is most likely because the unsuccessful validation attempt is preventing a further postback.
See also: Why won't my form post back after validation?
There is a variable called Page_BlockSubmit which is set to true when client side validation fails:
function Page_ClientValidate(validationGroup) {
....
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
So when a __doPostBack occurs as part of, say, an OnSelectedIndexChanged of a DropDownList, there is this check:
function ValidatorCommonOnSubmit() {
....
var result = !Page_BlockSubmit; /* read the value */
....
Page_BlockSubmit = false; /* reset it */
return result;
}
Which will block the first time, but then clear the flag, so the next postback attempt should work.
The workaround, in my case, for a DropDownList's OnSelectedIndexChanged event, was to have a snippet added to its client-side onchange event:
<asp:DropDownList runat="server" ID="SomeDropDownList" OnSelectedIndexChanged="AlwaysDoSomething"
onchange="resetValidationState(this);">
....
</asp:DropDownList>
<script type="text/javascript">
function resetValidationState() {
// clear any postback blocks, which occur after validation fails:
window.Page_BlockSubmit = false;
}
</script>
You might get away with putting that snippet into the onchange itself.
except that after this button has been clicked no other button can cause a postback unless the validation errors have been corrected. So, btnDelete, which should not require validation of the textboxes, cannot postback until the textbox values are corrected
Don't see that behavior with following code..
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1" ValidationGroup="pc">
</asp:RequiredFieldValidator>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" Width="150" CausesValidation="true" ValidationGroup="pc" />
<asp:Button runat="server" ID="btnDelete" Text="Delete" CausesValidation="false" />
I could be totally off base here - but i think I see the problem. (I work mainly with devexpress controls so the rules can be a bit different). When validation fails, the whole page is set to invalid, so no postbacks can occur. Can it be since the delete button is not causing any validation, its not re validating after those editors have been changed to be valid?

How to show regular expression validation's message after button click only?

Below is my html code. I have a email textbox and there is a login button. I have added a required field validator and regular expression validator for email textbox.
The problem is that when I type some thing in the email textbox browser's auto suggestion shows some list of emails. When I select any of those emails by using down arrow key and enter key it shows the error message for regular expression validation even though email is in proper format.
<asp:RequiredFieldValidator ID="reqValUserName" runat="server"
ErrorMessage="Email is required!"
ControlToValidate="txtUserName"
ValidationGroup="validateCredential"
Display="Dynamic">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Static">
</asp:RegularExpressionValidator>
<asp:TextBox ID="txtUserName" runat="server"
TabIndex="1" CssClass="inputCredential" MaxLength="60"
AccessKey="E"
ValidationGroup="validateCredential">
</asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CssClass="btnPrimary"
Text="Login" onclick="btnLogin_Click"
ValidationGroup="validateCredential"/>
In this image as you see if I select the email from the suggestion and press enter it is showing the wrong email validation message.
Can anyone please let me know, how to stop this kind of message display?
If there is any clarification needed regarding the question then please add it as a comment.
You could add the EnableClientValidation="false" attribute to the regex validator so that it only checks the format on the server after the other validators have been passed.
Or follow the advice here:
What determines the order validators fire in?
Also add regular expression validator
for email text box
<asp:RegularExpressionValidator ID="regtxtPrimaryEmail" runat="server" ControlToValidate="txtEmailId"
Display="Dynamic" CssClass="cssVal" ToolTip="Invalid email." ValidationGroup="registration"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
Then it will not submit until the email format correct.
It seems your some controls has autopostback="true" and your these controls are in update panel if not then what you can do is..Remove the display properties of all the validation controls and on btnLogin_Click Event call Validate(); Method.
Also read more In Depth detail on Validators on MSDN
you'll certainly get your answer....
Thanks for all your answers and suggestions.
Below is what I have done after going through all the answers.
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Dynamic" EnableClientScript="false">
</asp:RegularExpressionValidator>
As you can see, I have added EnableClientScript="false" so that the error message will not be shown when I type half of email and select from auto suggestion and press enter.
Now the problem was it was always checking for whether entered credentials are correct of not as it was doing validation in server side. So I had some unnecessary code execution and database interaction.
So in click event handler of login button I did following change.
if(Page.IsValid)
{
// My credential check code
}
So the above block of code will run code for checking correctness of entered credentials only if they are in proper format.
But I am still looking for a better answer. This is only a work around. Because when it comes to performance server side validation can never match client side validation. Here I am compromising with usability. As I want user to be notified immediately after he/she enters a wrong formatted email. This can be achieved by using javascript, but I wonder if there is any way we can achieve it using validator controls..
This is happening because the client-side REV is validating on the partial input. For example, in the above illustration, the REV is validating "r" as its input. In order to verify this,
type in the entire email address "rupeshn#aol.com" >> then
select the suggested email using the down arrow >> then
hit the enter key.
The REV will not complain this time.
As for the solution: implement the REV in javascript. Add a label next to the textbox for error message. Call the js when the cursor exits the textbox. If the validation fails, find the label in the js and add the error message.
Just see the properties of the validator there you will find 'Display' property under Appearance section, set it to dynamic and VOLA!!

Custom validation not working with delete buttons?

In a ListView, I have a CustomValidator set up to validate a field whenever a button with CommandName="Delete" is clicked.
<ItemTemplate>
<asp:TextBox ID="NameTextBox" Text=<%# Eval("Name") %> runat="server" />
<asp:Button ID="DeleteButton" Text="Delete" CommandName="Delete" ValidationGroup="Delete" runat="server" />
<asp:CustomValidator ValidationGroup="Delete" SetFocusOnError="true" Display="Dynamic" OnServerValidate="CustomValidator_ServerValidate" runat="server">You can't delete this.</asp:CustomValidator>
</ItemTemplate>
However, the error message is never displayed and the processing continues. What's strange is that the custom validation method is called, finds the field, and properly sets up e.IsValid to false. It does not matter whether I check Page.IsValid or not, because the error message is not displayed anyway.
It works if I remove the CommandName="Delete" from the button.
With Google I found the following solution, which seems to indicate someone has had a similar issue:
http://devio.wordpress.com/2007/12/11/formview-delete-button-and-customvalidators/
But I want to make sure that this solution is the way to go. I mean, is custom validation really not supposed to work with a delete button in a databound control, seriously?
I've alrealy heard about a problem like that, he solved it by doing it entirely differently. Like, instead of the customValidator, he puts a Label set EnableViewState="False" and Visible="False" and he check on the delete event the conditions and put the response back into the label. Maybe it can't works for you too?
But, if you realy ask "Why?????", I know he didn't find the exact reason ...

Resources