How to show regular expression validation's message after button click only? - asp.net

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!!

Related

RequiredFieldValidator have to click twice

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.

Server side validation

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.
So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".
EDIT:
This is the code:
<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server" ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank." ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>
You need to provide the markup for your Button / Link control as well.
The 'CausesValidation' attribute is not supposed to be used on TextBox controls.
The button you click needs to have that attribute set to "True".
Please provide that markup and then I can advise on the alternate server side validation.
To enable Client-side Validation, set the EnableClientScript="true" on the RequiredFieldValidator.
You should also always validate on the server side too. But the RequiredFieldValidator doesn't let you do any special-handling server-side. Just check if Page.IsValid(). This will return false if the field is not supplied.
If you want to do custom validation, use a CustomValidator.

RegularExpressionValidation error message not clear after value is fixed

I am using a regular expression validator to validate several fields on an asp.net form. Here is an example:
<asp:RegularExpressionValidator runat="server"
ID=RegularExpressionValidatortxtEMAIL ControlToValidate="txtEmployerEmail"
ErrorMessage="EMail Address - must be valid"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic" ></asp:RegularExpressionValidator>
The problem is that after the user enter a invalid value and then corrects it with a valid value, the error message persists until a postback is generated.
Is there any fix for this?
There's nothing wrong with that validator tag - I've just used it in a page and it works fine. You understand that the validator only gets fired when the control loses focus... It could be something else in your page that's causing the problem, perhaps a JavaScript error?

ASP.NET validators alignment issue

I am developing contactus webpage which have a input field called Email. It is validated against a required field validator and regular expression validator with appropriate messages.
Required: Enter Email
Regular Expression: Invalid Email
I am setting these two as given below:
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<font color="#FF0000">*</font>
<asp:RequiredFieldValidator ID="rfvemail" CssClass="error_text" ControlToValidate="txtEmail"
runat="server" ErrorMessage="Enter email address."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revemail" runat="server" ControlToValidate="txtEmail"
ErrorMessage="Invalid Email" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
My problem is both Enter Email and Invalid Email is occupying its own space. For Ex: If I leave email as empty space and press submit, Enter Email is displaying right next to it. If I enter invalid email(xxx), Enter Email is off but taking the space, Invalid Email message is displayed after these space taken by 'Enter Email' before.
Is there any way to remove this space??
Mahesh
Set Display = "Dynamic" on it.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.display%28v=VS.100%29.aspx
Use Diplay = "Dynamic"
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error message only in the
ValidationSummary control)
Static (the control displays an error message if validation fails. Space is
reserved on the page for the message even if the input passes validation.
Dynamic (the control displays an error message if validation fails. Space is not
reserved on the page for the message if the input passes validation
If I understand the question correctly, I think the answer is to set the Display property to Dynamic.
If you're using ASP.NET Themes, you can set this as the default for all validators in your Theme using a Skin file, so you never have to worry about it again.

how to reset input field after validation fails?

I have a validator for a date input field. If the input is not in the MM/DD/YYYY format then it should throw an error and clear the input. I have tried Text="" property, but that doesn't work. And setFocusOnError is only working once.If I hit tab twice the field is losing foucs . Any ideas?
<asp:RegularExpressionValidator ID="startDateValidator" Display="Dynamic"
ControlToValidate="dateStartDate" ValidationExpression="([0-9]|1[012])[/]([0-9]|[12][0-9]|3[01])[/](19|20)\d\d"
ErrorMessage="Start Date should be in MM/DD/YYYY format" runat="server" SetFocusOnError="true"
/>
EDIT: I want to know if this is possible using asp's validator controls.And why SetFocusOnError is not working as it's supposed to?
You should always validate on server side, additionally you can of course validate on client side (usability).
You can clear the textbox via javascript, but consider a user could have disabled javascript. That's also why you should always validate on server side.
<script language=JavaScript>
<!--
function clear_textbox()
{
document.text_form.u_input.value = "";
}
-->
</script>
You can run this script, you need to change u_input to your controls name.

Resources