ASP.Net Custom Validator failed ,form gets submitted - asp.net

I have made a form in which there are two RAD DateTimePicker Controls . One is for Start-DateTime and other is for End Date Time. Inside Custom Validator, I have Compared the Date Time Picked So far and hence made it valid or invalid accordingly its Server Validate event code goes like this.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Its Design Code goes like this.
<telerik:RadDateTimePicker ID="rdpStartDate" runat="server" AutoPostBackControl="Both" onselecteddatechanged="rdpStartDate_SelectedDateChanged">
<TimeView CellSpacing="-1" Culture="en-IN">
</TimeView>
<TimePopupButton HoverImageUrl="" ImageUrl="" />
<Calendar UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x">
</Calendar>
<DateInput AutoPostBack="True" DateFormat="dd-MM-yyyy" DisplayDateFormat="dd-MM-yyyy">
</DateInput>
<DatePopupButton HoverImageUrl="" ImageUrl="" />
</telerik:RadDateTimePicker>
<asp:Label ID="Label2" runat="server" Text=" To" CssClass="h_text"></asp:Label>
<telerik:RadDateTimePicker ID="rdpEndDate" runat="server" onselecteddatechanged="rdpEndDate_SelectedDateChanged" AutoPostBackControl="Both">
<TimeView CellSpacing="-1" Culture="en-IN"></TimeView>
<TimePopupButton ImageUrl="" HoverImageUrl=""></TimePopupButton>
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x"></Calendar>
<DateInput DisplayDateFormat="dd-MM-yyyy" DateFormat="dd-MM-yyyy" AutoPostBack="True"></DateInput>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
</telerik:RadDateTimePicker>
Validator Source Code in designer is like this.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
I want to ask that even when custom validator fails, My form gets submitted with faulty values. What can be the reason? How can I avoid that?

With Server validator Event like:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You have to check on your server event as well like:(For example if you are using your validator with button click then)
protected void btn_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Write("Page is valid.");
}
else
{
Response.Write("Page is not valid!");
}
}
My suggestion: Telerik has a good client side support as well so I suggest you to use client side validation of custom validator.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
ClientValidationFunction="CheckDates"
SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
then in Javascript:
function CheckDates(sender, args)
{
var cltRdpEndDate= $find("<%=rdpEndDate.ClientID %>");
var cltRdpStartDate= $find("<%=rdpStartDate.ClientID %>");
if(cltRdpEndDate.get_dateInput().get_selectedDate()< cltRdpStartDate.get_dateInput().get_selectedDate())//if your condtion fails here
{
args.IsValid = false;
return;
}
args.IsValid = true;
}

Related

CustomValidator doesnt display a message unless I use a validation summary

I want to output a message in case if an invalid date was supplied.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
DateTime temp;
if (DateTime.TryParse(args.Value, out temp))
{
args.IsValid =true;
}
else
{
args.IsValid = false;
}
}
catch (Exception ex)
{
args.IsValid = false;
}
}
I expect the output message to be located near the field.
Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.
Is there away display the message without the validation summary?
Is there away display the message without the validation summary?
You will need to use Text attribute instead of ErrorMessage.
<asp:CustomValidator ID="CustomValidator1"
ControlToValidate="RegistrationFromTextBox2"
OnServerValidate="CustomValidator1_ServerValidate"
ValidationGroup="NewMailingItem"
runat="server"
Text="The date is invalid">
</asp:CustomValidator>
FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"
placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
ID="RegistrationFromCompareValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="RegistrationFromTextBox2"
Text="The date is invalid">
</asp:CompareValidator>

ASP.NET Forms CustomCustomvalidator - always correct value

I've created simple page in ASP.NET Forms and I need to use CustomValidator control. Here's the code:
Page.aspx
<asp:ListBox
ID="listControl" runat="server"
ClientIDMode="Static"
onchange="toggleButton(this, document.getElementById('remove'))" />
<asp:CustomValidator
ID="fmValidator"
ControlToValidate="listControl"
CssClass="IncorrectResult"
runat="server"
ValidateEmptyText="True"
ErrorMessage="..."
Text="..."
OnServerValidate="Validator_OnServerValidate" />
Page.aspx.cs
protected void Validator_OnServerValidate(object source, ServerValidateEventArgs args)
{
if(isAdmin)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
The point is that I can catch an event in Validator_OnServerValidate with proper data but whatever I put in args.IsValid (I mean true or false) it always returns correct value - on the webpage everything is correct. What is wrong?
That was because page didn't reload on validating. All I had to do was enable client side validation.

Custom validator message not displaying

VS2013, WebForms, .NET 4.51
I have a FormView defined and in my EditTemplate I have as follows:
<div class="form-group">
<asp:Label ID="lblClientClassification" CssClass="col-md-2 control-label" runat="server" for="cblClientClassifications" Text="Kind"></asp:Label>
<div class="col-md-5">
<asp:CheckBoxList ID="cblClientClassifications" runat="server"></asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="XXXX" ValidationGroup="Default" OnServerValidate="cfvClientClassifications_OnServerValidate"></asp:CustomValidator>
</div>
and then in the code behind:
protected void cfvClientClassifications_OnServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
The OnServerValidate is firing and I am getting to set the validator to invalid as well as setting the error message (Page.IsValid is also false as expected). However, the error text is not displaying. When I view the page source I see:
<span id="ctl00_cphMainContent_fvData_cfvClientKinds" class="label label-danger" style="display:none;">XXXX</span>
instead of the error message I set as well as the fact that it is not visible.
Has anyone got any pointers here on how to track this down? I have looked at similar questions of SO but none of the comments seem to apply. Is this related to FormView perhaps?
Try your control without the CssClass="label label-danger" bootstrap first, and use the code below to check your boxes:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cfvClientKinds.ErrorMessage = "Hey! this is a new message";
}
and I guess you call this line before you fire the above event:
protected void btnValidate_Click(object sender, EventArgs e)
{
Page.Validate();
}
In Short, I think that your problem is either related to your way of finding cblClientClassifications checkBoxList or other code that you haven't stated above.
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
I decided to try out your case and created a new webform added formview and bind it to northwind categories table then inside edititemtemplate I added a checkboxlist and populated it manually. added CustomValidator double clicked it copied your codebehind and it works for me except for the findcontrol part: GuiClientClassificationsFind();
Here is the formview:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1">
<EditItemTemplate>
...
<asp:CheckBoxList ID="cblClientClassifications" runat="server">
<asp:ListItem>Bir</asp:ListItem>
<asp:ListItem>iki</asp:ListItem>
<asp:ListItem>Üç</asp:ListItem>
<asp:ListItem>Dört</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="CustomValidator" OnServerValidate="cfvClientKinds_ServerValidate"></asp:CustomValidator>
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:FormView>
And codebehind with your code:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
I Ali Shahrokhi's method is shorter and works as well as yours..
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
if you check as you entered edititemtemplate in formview you'll see before submitting that your customvalidators span will be there just as you mentioned that's because server hasn't sent it to the client yet somehow.

how to disable server side validation on asp.net web forms from browser?

I wanted to disable asp.net validation server controls from browser. I checked online but did not find any way to disable the server side validation; it can be disabled only on the client side using JS/jQuery.
Here is the scenario: I have a checkbox and selecting which displays a set of text boxes. Only if the checkbox is checked, required field validator should fire for the text boxes. I don't want to call a postback on checkbox. Actually those chceck boxes will be generated with jQuery templating so postback is not an option to enable disable validtion.
I would like to know whether there is any way we can enable disable the .CausesValidation property for the controls from browser using some setting? Or is there a way to capture the controls which are to be considered for validation slectively in some event before page_load?
[Update]
Based on Accepted answer, here is my solution:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" ControlToValidate="textbox1" runat="server"
ErrorMessage="enter text"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" ControlToValidate="textbox2" runat="server"
ErrorMessage="enter text for 2"></asp:RequiredFieldValidator>
<asp:CheckBox ID="check1" runat="server" Text="choose" />
<asp:Button ID="submitBtn" runat="server" OnClick="submitBtn_Click" Text="submit" />
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:ValidationSummary ID="summary" runat="server" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
req1.Enabled = false;
req2.Enabled = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
Response.Write("valid form");
}
else
{
Response.Write("invalid form");
}
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (check1.Checked)
{
req1.Enabled = true;
req1.Validate();
}
}
The solution for me would be to use a CustomValidator with a OnServerValidate method.
In the OnServerValidate method I would check if the checkbox is checked, in that case I would verify if the textboxes are filled. It is not necessary to do any change in the CausesValidation property.
The only condition is not to include the property "ControlToValidate". A CustomValidator does not fire if the textbox is empty that's why.
So the code would be like this:
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="prueba" />
<asp:CheckBox ID="chb" runat="server" Text="Check" />
<asp:TextBox ID="txbBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:Button ID="btn" runat="server" Text="Prueba" />
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (chb.Checked)
{
if (txbBox.Text == String.Empty)
{
cvBox.IsValid = false;
}
}
}

How do I make a checkbox required on an ASP.NET form?

I've done some searching on this, and I've found several partial answers, however nothing that gives me that warm fuzzy "this is the right way to do this". To answer the most frequently occurring complaint against this question: "checkboxes can have two legitimate states - checked and unchecked", this is an "I accept the terms and conditions..." checkbox which must be checked in order to complete a registration, hence checking the box is required from a business logic standpoint.
Please provide complete cut-n-paste ready code fragments with your response! I know there are several pieces to this -- the CustomValidator (presumably), the code-behind, some javascript and possibly a check for IsValid, and the frustrating part for me is that in each example I've seen, one of these critical pieces is missing!
javascript function for client side validation (using jQuery)...
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}
code-behind for server side validation...
protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = MyCheckBox.Checked;
}
ASP.Net code for the checkbox & validator...
<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
OnServerValidate="CheckBoxRequired_ServerValidate"
ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
and finally, in your postback - whether from a button or whatever...
if (Page.IsValid)
{
// your code here...
}
C# version of andrew's answer:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please accept the terms..."
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:CheckBox ID="CheckBox1" runat="server" />
Code-behind:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = CheckBox1.Checked;
}
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return #"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.
The .ascx:
<script type="text/javascript">
function checkAgreement(source, args)
{
var elem = document.getElementById('<%= chkAgree.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
function checkAge(source, args)
{
var elem = document.getElementById('<%= chkAge.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />
<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAgreement">
You must agree to the terms and conditions.
</asp:CustomValidator>
<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAge">
You must be 18 years or older to continue.
</asp:CustomValidator>
And the codebehind:
Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
e.IsValid = chkAgree.Checked
End Sub
Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
e.IsValid = chkAge.Checked
End Sub
I typically perform the validation on the client side:
<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server" />
<asp:CustomValidator id="vTerms"
ClientValidationFunction="validateTerms"
ErrorMessage="<br/>Terms and Conditions are required."
ForeColor="Red"
Display="Static"
EnableClientScript="true"
ValidationGroup="vg"
runat="server"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
<script>
function validateTerms(source, arguments) {
var $c = $('#<%= chkTerms.ClientID %>');
if($c.prop("checked")){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
Non-javascript way . .
aspx page:
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>
Code Behind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If Not CheckBox1.Checked Then
args.IsValid = False
End If
End Sub
For any actions you might need (business Rules):
If Page.IsValid Then
'do logic
End If
Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(

Resources