asp.net "compare validator" validation - asp.net

I am trying to validate fromdate & todate textboxes in asp.net using compare validator
my script is:
<table><tr><td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text="Fromdate:"> </asp:Label>
<asp:TextBox ID="fromdatetxt" runat="server" Height="21px" Width="103px" ></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="fromdatetxt_CalendarExtender" runat="server"
Enabled="True" TargetControlID="fromdatetxt">
</ajaxToolkit:CalendarExtender>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Todate:"></asp:Label>
<asp:TextBox ID="todatetxt" runat="server" Height="21px" Width="105px" ></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="todatetxt_CalendarExtender" runat="server"
Enabled="True" TargetControlID="todatetxt">
</ajaxToolkit:CalendarExtender>
</td>
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="None" ErrorMessage="From date cannot be greaterthan To date"
operator = "LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>
<td>
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" ValidationGroup="DateValidation" />
<asp:ValidationSummary ID="ValidationSummaryDate" ShowMessageBox="true" ShowSummary="False"
ValidationGroup="DateValidation" runat="server" /></td></tr></table>
</asp:Panel>
This is working fine! but I'm getting message box only when click the button. But I want to get message box the moment I clicked date in Todate in calendar control, and the textboxes must get clear. please help me out .

You can solve your problem using "Page_ClientValidate" function of javascript and "OnClientDateSelectionChanged" event of CalendarExtender.
You do not need to change your CompareValidator i.e.
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="None" ErrorMessage="From date cannot be greater than To date"
Operator="LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>
You need to add OnClientDateSelectionChanged event to your CalendarExtender as
<ajaxtoolkit:CalendarExtender id="todatetxt_CalendarExtender" runat="server" enabled="True"
targetcontrolid="todatetxt" OnClientDateSelectionChanged="validate" >
"validate" here is a javascript function. In that function you need to use "Page_ClientValidate" method of javascript as
var validate = function () {
var isValid = Page_ClientValidate("DateValidation"); //parameter is the validation group
if (!isValid) {
$("#<%= todatetxt.ClientID %>").val(''); //jquery to clear the textbox
}
}
You can modify the "validate" function as per your convenience.
I hope this helped.
Regards,
Samar

add Display="Dynamic" in validator
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="Dynamic" ErrorMessage="From date cannot be greaterthan To date"
Operator="LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>

Related

How to make a extender calendar unable to select a date base on a selected date?

How can I make user unable to select an end date before the an start date?
<asp:Label ID="lblStartDate" runat="server" Text="Start Date: " CssClass="labelClass"></asp:Label>
<asp:TextBox ID="tbStartDate" runat="server" ReadOnly="True"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalExtStartDate" runat="server" Format="dd/MM/yyyy" TargetControlID="tbStartDate" />
<asp:Label ID="lblEndDate" runat="server" Text="End Date: " CssClass="labelClass"></asp:Label>
<asp:TextBox ID="tbEndDate" runat="server" ReadOnly="True"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalExtEndDate" runat="server" TargetControlID="tbEndDate" Format="dd/MM/yyyy" />
In my .aspx.cs I've got but it still doesn't work.
if (!IsPostBack)
{
CalExtStartDate.StartDate = DateTime.Now.AddDays(-7);
CalExtEndDate.StartDate = CalExtStartDate.SelectedDate;
}
I believe that you can use a compare validator paired with 2 required field validators (one for each date textbox):
<asp:TextBox ID="tbStartDate" runat="server" ReadOnly="True"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="End Date required" ID="requiredDate1" ControlToValidate="tbStartDate" />
<asp:TextBox ID="tbEndDate" runat="server" ReadOnly="True"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="Start Date required" ID="requiredDate2" ControlToValidate="tbEndDate" />
<asp:CompareValidator runat="server" ID="compareValidator1" ErrorMessage="End date must be after start date" ControlToCompare="tbStartDate" ControlToValidate="tbEndDate" Operator="GreaterThan" Type="Date" />

user control (.ascx) with a textbox and a ajax calendar extender - end date should be greater than start date

I have a user control (.ascx) with textbox and ajax calendar extender . I used this twice for start date and end date in web forms. How to compare these dates using compare validator control?
my code:
.ascx
<asp:TextBox ID="txtDatePicker" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="Image1" ImageUrl="~/Images/calendar.png" AlternateText="Click to show calendar" />
<ajaxToolkit:CalendarExtender Format="dd/MM/yyyy" ID="CalendarExtender1" TargetControlID="txtDatePicker" runat="server" PopupButtonID="Image1" />
.aspx
Start Date <uc1:datePicker ID="datePickerSD" runat="server" >
End Date <uc1:datePicker ID="datePickerED" runat="server" />
<asp:CompareValidator ID="compareValidatorDate" runat="server" ControlToValidate="datePickerED.UniqueID" ControlToCompare="datePickerSD.ClientID" CultureInvariantValues="true"
ErrorMessage="End date should be greate than start date" Operator="GreaterThanEqual" SetFocusOnError="true" Type="Date"> </asp:CompareValidator>
getting error:
you should use custom validator in which you specify javascript function that should be executed upon validation. in this function u can do whatever logic u want.
<asp:CustomValidator ID="custDateOfBirth" runat="server" ControlToValidate="txtBirthDate" ClientValidationFunction="CheckDate" ErrorMessage="Enter less than the current date" CssClass="ClsRedtext" SetFocusOnError="true" Type="Date" ></asp:CustomValidator>
Solved:
<asp:CompareValidator ID="compareValidatorDate" runat="server" ControlToValidate="datePickerED$txtDatePicker" ControlToCompare ="datePickerSD$txtDatePicker" CultureInvariantValues="true"
ErrorMessage="End date should be greater than start date" Operator="GreaterThanEqual" SetFocusOnError="false" Type="String" Display="Dynamic" EnableClientScript="true" Font-Size="Small" ForeColor="Red"></asp:CompareValidator>

asp.Net ValidationGroup validating correctly except on Enter key

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

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

Two Validation Groups in a single button without client click event

In a multigrid I am validating two controls like date and amount. It is validating correctly when I press the tabevent. When I press the save button it is not validating. I am using two validations groups and two validation summary. Then in save button Ialso tried onclientclick() function with javascript it is working fine but if I give the correct value in date and amount records, it is not saving. how to over come this.
Date
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox ID="txtDate" Text='<%# Bind("AD_REF_DATE") %>' runat="server" CausesValidation="true"
ValidationGroup="group" Width="80px" AutoPostBack="true" OnTextChanged="txtDate_TextChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CompareValidator ID="dateValidater" runat="server" ControlToValidate="txtDate"
Operator="DataTypeCheck" Type="Date" ValidationGroup="group" EnableClientScript="true"
ErrorMessage="Please enter a valid date (mm/dd/yyyy)." SetFocusOnError="true" Display="None">*</asp:CompareValidator>
</ItemTemplate>
</asp:TemplateField>
Amount
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" MaxLength="17" Text='<%# Bind("AD_AMOUNT") %>' CausesValidation="true"
ValidationGroup="req" runat="server" AutoPostBack="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RegularExpressionValidator ID="regVal1" runat="server" ControlToValidate="txtAmount"
ErrorMessage="Format(13int,5deci)" ValidationExpression="^[1-9]\d{0,12}(\.\d{1,2})?%?$"
ValidationGroup="req" Display="None" EnableClientScript="true" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
validations summary:
<asp:ValidationSummary ID="ValidationSummary3" runat="server" ValidationGroup="req"
HeaderText="Amount:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="group"
HeaderText="Date:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
button save:
<asp:Button ID="ButtonSave" runat="server" CssClass="button" CausesValidation="true" Text="<%$Resources:TJFAS501, ButtonSave %>"
OnClick="ButtonSave_Click" TabIndex="6" />
How to validate this in the button save also two popup box should be shown?
You might want to try firing the validate function for both groups manually via the button's OnClientClick since you have two validation groups you need to validate against. Currently your validation is not firing because you do not have any ValidationGroup assigned to your button so it is just looking for validators with no ValidationGroup defined (yours groups are: group and req).
You can call Page_ClientValidate() via javascript to fire off the validation checks manually (be sure to set CauseValidation on your button to false) and it has an optional parameter that takes the validation group.
<asp:Button ID="yourButton" runat="server" OnClick="ButtonSave_Click"
CausesValidation="false" TabIndex="6"
OnClientClick="return (Page_ClientValidate('group') && Page_ClientValidate('req'));" />
You can read more about Page_ClientValidate on MSDN.
It would be easier to just have one validation group for each action (eg. your button) but I assume you need two groups for some reason.
Try this..
<script type="text/javascript">
function Validate() {
var isValid = false;
isValid = Page_ClientValidate('Group1');
if (isValid) {
isValid = Page_ClientValidate('Group2');
}
return isValid;
}
</script>

Resources