asp.Net ValidationGroup validating correctly except on Enter key - asp.net

I've seen a variety of questions here that are very close to this issue but none which seem to fit this specific scenario.
Description:
I have ID and Password fields with a Log On button in the Master page. These are in the "LoginValidationGroup" and they work fine.
Now, in the Default.aspx, I have an email TextBox and submit button that are in the "NotifyMeValidation" group, and they also work, BUT not if you hit the enter key rather than the submit button. The Submit button works fine - Enter key ... not so much.
The Enter key causes the validation to occur on the LoginValidationGroup, even though the TextBox is set to CausesValidation="true", and it is in the NotifyMeValidation group.
I guarantee people are going to enter an email in that box and hit Enter. I would!!! And when they do, they're going to see a callout balloon at the top telling them the User ID is required.
What's my error here? If I need to post the actual code I can do so.
Actually, let me just go ahead and do that.
From the Default.aspx:
<asp:RequiredFieldValidator
runat="server"
ValidationGroup="NotifyMeValidation"
ID="EmailRequiredValidator"
ControlToValidate="SenderEmailTextBox"
ErrorMessage="Email is Required"
Display="None" />
<ajaxToolkit:ValidatorCalloutExtender
runat="Server"
PopupPosition="Left"
ID="EmailRequiredValidatorExtender"
Width="185px"
TargetControlID="EmailRequiredValidator"
WarningIconImageUrl="/Images/warning.gif" />
<asp:Label ID="SenderEmailLabel" runat="server" ssociatedControlID="SenderEmailTextBox" EnableViewState="false" Text="Email:"></asp:Label>
<asp:TextBox ID="SenderEmailTextBox" runat="server" ValidationGroup="NotifyMeValidation" Width="350" BackColor="#cccccc" CausesValidation="true"></asp:TextBox>
<br /><br />
<asp:Button ID="SubmitButton" runat="server" ValidationGroup="NotifyMeValidation" EnableViewState="false" CssClass="submit" Text="Send" CausesValidation="true" OnClick="btnSubmit_Click" />
From the Master page:
<asp:Label CssClass="LoginHeading" ID="UserNameLabel" runat="server" AssociatedControlID="UserNameTextbox">UserName: </asp:Label>
<asp:TextBox CssClass="LoginTextBox" ID="UserNameTextbox" runat="server" ValidationGroup="LoginValidation" CausesValidation="True"></asp:TextBox>
<asp:Label CssClass="LoginHeading" ID="PasswordLabel" runat="server" AssociatedControlID="PasswordTextbox">Password: </asp:Label>
<asp:TextBox CssClass="LoginTextBox" ID="PasswordTextBox" runat="server" TextMode="Password" ValidationGroup="LoginValidation" CausesValidation="True"></asp:TextBox>
<asp:Button CssClass="LoginHeading" ID="LoginButton" runat="server" Text="Button" CommandName="Login" ValidationGroup="LoginValidation" CausesValidation="True" onclick="LoginButton_Click" />
And the Master page validators...
<asp:RequiredFieldValidator runat="server" ID="UIDRequired"
ValidationGroup="LoginValidation"
ControlToValidate="UserNameTextbox"
Display="None"
ErrorMessage="<b>Required Field Missing</b><br />A User ID is required." />
<ajaxToolkit:ValidatorCalloutExtender
runat="Server"
ID="UIDValidationExtender"
PopupPosition="Left"
Width="185px"
TargetControlID="UIDRequired"
WarningIconImageUrl="/Images/warning.gif" />
<asp:RequiredFieldValidator runat="server" ID="PWRequired"
ValidationGroup="LoginValidation"
ControlToValidate="PasswordTextbox"
Display="None"
ErrorMessage="<b>Required Field Missing</b><br />A password is required." />
<ajaxToolkit:ValidatorCalloutExtender
runat="Server"
ID="PWValidationExtender"
PopupPosition="Left"
TargetControlID="PWRequired"
Width="185px"
WarningIconImageUrl="/Images/warning.gif" />
<asp:CustomValidator
runat="server"
Display="None"
ValidationGroup="LoginValidation"
ID="CustomUserExistsValidator"
ControlToValidate="UserNameTextbox"
ErrorMessage="<b>Invalid UserID!</b><br />User ID doesn't exist. Please try again.<br />"
OnServerValidate="CustomCheckUserExists"/>
<ajaxToolkit:ValidatorCalloutExtender
runat="server"
PopupPosition="Left"
ID="UserIDCalloutExtender"
TargetControlID="CustomUserExistsValidator"
Width="185px"
WarningIconImageUrl="/Images/warning.gif" />
<asp:CustomValidator
runat="server"
ID="CustomPWValidator"
Display="None"
ValidationGroup="LoginValidation"
ControlToValidate="PasswordTextbox"
ErrorMessage="<b>Invalid Password!</b><br />Please try again.<br />"
OnServerValidate="CustomValidatePassword"/>
<ajaxToolkit:ValidatorCalloutExtender
runat="server"
PopupPosition="Left"
ID="PWCalloutExtender"
TargetControlID="CustomPWValidator"
Width="185px"
WarningIconImageUrl="/Images/warning.gif" />
<asp:CustomValidator
runat="server"
ID="CustomUserApprovedValidator"
Display="None"
ValidationGroup="LoginValidation"
ControlToValidate="UserNameTextbox"
ErrorMessage="<b>Approval Error!</b><br />This UserID exists, but is not yet approved.<br />"
OnServerValidate="CustomCheckUserApproved"/>
<ajaxToolkit:ValidatorCalloutExtender
runat="server"
PopupPosition="Left"
ID="UserApprovedCalloutExtender"
TargetControlID="CustomUserApprovedValidator"
Width="185px"
WarningIconImageUrl="/Images/warning.gif" />

Try adding an <asp:Panel> around each set of controls and setting the DefaultButton property to the ID of the button you want to click when the users hits Enter.

Just to explain what is happening here, the aspx's default button is being fired when you press enter on the textbox. To handle this you could you could fire some jQuery code when the enter key is clicked on the textbox, this code will then perform the click on the specific button that you require. Check this

Related

How to make validator's message appear nearby another control?

I have a validator with a bound text field (it's set via ControlToValidate). How can I make the validator's error message appear nearby another control (a label above this text field)?
Just put the validator control nearby the control where you want to show the message i.e. wherever you want to show the message just put the validator control there.
In the following example I am showing validation message near some other control not near the text box.
<form id="form1" runat="server">
<asp:Label ID="lblNameRequired" runat="server" Text="*Name :"></asp:Label>
<asp:TextBox ID="txtNameRequired" runat="server" ValidationGroup="Validation"></asp:TextBox>
<br />
<asp:Label ID="lblGenderRequired" runat="server" Text="*Gender :"></asp:Label>
<asp:DropDownList ID="ddlGenderRequired" runat="server" ValidationGroup="Validation">
<asp:ListItem Selected="True" Value="-1">--Select--</asp:ListItem>
<asp:ListItem Value="0">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
<asp:CompareValidator ID="CompareValidatorGender" runat="server" ControlToValidate="ddlGenderRequired"
Display="Dynamic" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
ValueToCompare="-1"></asp:CompareValidator>
<br />
<asp:Label ID="lblValidation" runat="server" Text="Fields marked with * are required"></asp:Label>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ControlToValidate="txtNameRequired"
Display="Dynamic" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate Input" ValidationGroup="Validation" />
<br />
</form>
Hope this helps you.

Multiple ValidationSummary and RequiredFieldValidators

I have two Validation Groups on my page, called "login" and "register". Each group has its own ValidationSummary control and there a number of RequiredFieldValidators too. The problem I have is that the form is validating both groups instead of just the one.
Here is the code (I have omitted a lot of HTML to simplify):
<div id="divRegisterBox">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="register" />
<asp:TextBox ID="tbRegisterEmail" runat="server" CssClass="form-control" placeholder="Required" ValidationGroup="register" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="tbRegisterEmail" runat="server" Text="" ErrorMessage="Please enter your email address." ValidationGroup="register" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" CssClass="errorMsg" ControlToValidate="tbRegisterEmail" runat="server" Text="" ErrorMessage="Please enter a valid email address." ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ValidationGroup="register" />
<asp:TextBox ID="tbRegisterPassword" name="result-password" runat="server" CssClass="form-control" placeholder="Required" TextMode="Password" ValidationGroup="register" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" CssClass="errorMsg" ControlToValidate="tbRegisterPassword" runat="server" Text="" ErrorMessage="Please enter your password." ValidationGroup="register" />
<asp:Button ID="btnMobileRegister" runat="server" Text="Register" OnClick="btnMobileRegister_Click" ValidationGroup="register" />
</div>
<div id="divLoginBox">
<asp:ValidationSummary ID="ValidationSummary2" runat="server" ValidationGroup="login" />
<asp:TextBox CssClass="form-control" name="result-email" ID="tbResultEmail" placeholder="Required" runat="server" ValidationGroup="login"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="tbResultEmail" runat="server" Text="" ErrorMessage="Please enter your email address." ValidationGroup="login" CssClass="errorMsg" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" CssClass="errorMsg" ControlToValidate="tbResultEmail" runat="server" Text="" ErrorMessage="Please enter a valid email address." ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ValidationGroup="login" />
<asp:TextBox CssClass="form-control" name="result-password" ID="tbResultPassword" placeholder="Required" TextMode="Password" runat="server" ValidationGroup="login"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" CssClass="errorMsg" ControlToValidate="tbResultPassword" runat="server" Text="" ErrorMessage="Please enter your password." ValidationGroup="login" />
<asp:Button ID="btnLoginMobile" runat="server" CssClass="btn btn-primary btn-block" Text="Login" OnClientClick="return MobileLoginSubmit();" ValidationGroup="login" OnClick="btnLoginMobile_Click" />
</div>
When I click either of the Button controls, the ValidationSummary controls show the validation messages for ALL validation controls on the page. It is as if they were all part of the same validation group.
I have tried adding CausesValidation="true" and "false" to the Buttons but it seemed to have no effect.
On your CodeBehind, you could do something like...
Page.Validate("register");
if (Page.IsValid)
{
//Keep calm and carry on
}
else
{
foreach (BaseValidator invalidField in validators)
{
//Do something with the invalid fields
}
}
That way, you're only validating that group that you specify.
Makes sense?
Your issue is Display="None".
In your divRegisterBox div, your validators all have Display="None", but your validators in your divLoginBox div do not.
Display="None" will not display the message inline. What you are seeing when you click the login button is not that both summaries are showing, but that the same error messages are being displayed in two different ways.

Required Field Validator on FileUpload Control

I have a form in which I have two textboxes and one fileupload control, I am using required field validator on one textbox and on Fileupload control, When I am clicking the submit button, its disabling the fileupload control and not showing any validation for it.
I also have second button for Cancel, clicking on which redirects to previous page, when I am clicking this button its also disabling the fileuploadcontrol.
Below is my code
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RequiredFieldValidator ID="rfvFileupload" ValidationGroup="validate" runat="server"
ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtSubj" runat="server" ></asp:TextBox><asp:RequiredFieldValidator
ID="rfvSubject" ControlToValidate="txtSubj" runat="server" Display="Dynamic"
EnableClientScript="true" ErrorMessage="* required" ValidationGroup="validate" />
<asp:Button ID="btnupload" runat="server" Text="Send" ValidationGroup="validate"
OnClick="btnupload_Click">
<asp:Button ID="btncancel" runat="server" Text="Cancel" OnClick="btncancel_Click"
/>
Try using no ValidadationGroup:
<asp:FileUpload ID="fupDocument" runat="server" Width="100%" />
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ErrorMessage="* Required Field" ControlToValidate="fupDocument">
</asp:RequiredFieldValidator>
I tried and work it.

asp.net required field validator

A required field validator should fire only after clicking a submit button
<asp:RequiredFieldValidator id="req" controltovalidate="txtphone" errormessage="please enter the details">
</asp:RequiredFieldValidator>
Youre missing runatserver on your code
Check this:
<form id="form1" runat="server">
Phone Number:<br />
<asp:TextBox runat="server" id="txtphone" />
<asp:RequiredFieldValidator runat="server" id="req" controltovalidate="txtphone" errormessage="Please enter your phone number!" />
<br /><br />
<asp:Button runat="server" id="btnSubmitForm" text="Ok" />
</form>
Regards
If you are using a button field try by applying Validation Group Property in both the validator and Button as follows
<asp:RequiredFieldValidator id="req" runate="Server" controltovalidate="txtphone" errormessage="please enter the details" ValidationGroup="g">
<asp:button id="btn" runat="server" validationgroup="g">

How to show validation control's Error messages in Alert box?

I am using 4 required field validators,4 regular expression validators and 4 compare validators for 4 text boxes.Is it possible to show error messages
in an alert or message box when validation fails?
If possible please send code sample.
Regards,
NSJ
<form id="form1" runat="server">
<asp:Label ID="lblNameRequired" runat="server" Text="*Name :"></asp:Label>
<asp:TextBox ID="txtNameRequired" runat="server" ValidationGroup="Validation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ControlToValidate="txtNameRequired"
Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblGenderRequired" runat="server" Text="*Gender :"></asp:Label>
<asp:DropDownList ID="ddlGenderRequired" runat="server" ValidationGroup="Validation">
<asp:ListItem Selected="True" Value="-1">--Select--</asp:ListItem>
<asp:ListItem Value="0">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
<asp:CompareValidator ID="CompareValidatorGender" runat="server" ControlToValidate="ddlGenderRequired"
Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
ValueToCompare="-1"></asp:CompareValidator>
<br />
<asp:Label ID="lblValidation" runat="server" Text="Fields marked with * are required"></asp:Label>
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate Input" ValidationGroup="Validation" />
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
ShowSummary="False" ValidationGroup="Validation" />
</form>
You should use the same ValidationGroup text on all validation controls and add a ValidationSummary with the ValidationGroup and ShowMessageBox="true"
Use the following code , just set the correct messeges that u want :
<asp:ValidationSummary ID="ValidationSummary1" ShowMessageBox ="true"
runat="server" />
<asp:textbox id="txt1" runat="server"></asp:textbox>
<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server"
controltovalidate="txt1" errormessage="Please Enter Only Numbers" validationexpression="^[-+]?\d+(\.\d+)?$">
</asp:regularexpressionvalidator>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt1"
errormessage="please enter txt1">*</asp:requiredfieldvalidator>
<asp:textbox id="txt2" runat="server"></asp:textbox>
<asp:regularexpressionvalidator id="RegularExpressionValidator2" runat="server"
controltovalidate="txt2" errormessage="Please Enter Only Charcters" validationexpression="^[a-zA-Z\s.]*$">
</asp:regularexpressionvalidator>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt2"
errormessage="please enter txt2">*</asp:requiredfieldvalidator>
<asp:textbox id="txt3" runat="server"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt3"
errormessage="please enter txt3">*</asp:requiredfieldvalidator>
<asp:Button ID="btnok" runat="server" Text="ok"/>
Don't do it. Users hate alert box error messages. It is a horrible UI design. Put the error messages on the form where the user can read them and they stay while the user makes changes or moves on without having to click on an alert box. Especially when there are multiple corrections to be made, they need to be able to read the errors while they make the corrections.
You can use this function
set parameters validation message and Control ID as parameters
protected void PopupMessage(string Msg, Control controlID)
{
ScriptManager.RegisterClientScriptBlock(controlID, controlID.GetType(), "msg", "alert('" + Msg + "');", true);
}
within the button click event you can this function according to your logic
protected void btnok_Click(object sender, EventArgs e)
{
if(TextBox1.Text=="")
PopupMessage("Name is Required", btnok);
}
please follow following code which is useful for me use ShowSummary property to reduce duplication of message into your pannel
<asp:ValidationSummary ID="VS1" ShowMessageBox="true" runat="server" ShowSummary="False" />
<asp:Label ID="lblUsername" runat="server" >User name</asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFV1" runat="server" ControlToValidate="txtUserName" ErrorMessage="Please Select Name" Display="None" SetFocusOnError="True">
</asp:RequiredFieldValidator><br />

Resources