Custom Validator Error - c#

I tried creating a custom validator to validate a checkbox and got this error:
"Control 'cbVerify' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated."
Here is the front end code i have for this:
<li>
<asp:CheckBox ID="cbVerify" runat="server" Text="I certify that the information entered on this form is correct and accurate." />
</li>
<li>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please check" Display="Dynamic" ControlToValidate="cbVerify" OnServerValidate="CustomValidator1_ServerValidate" CssClass="ValidationError"></asp:CustomValidator>
</li>
Back end:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = cbVerify.Checked ;
}
Could i get some help figuring this out?

Remove the ControlTovalidate value from CustomValidator1. it does not need to be there for checkboxes.
MSDN reference
Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. The ID must refer to a control within the same container as the validation control. It must be in the same page or user control, or it must be in the same template of a templated control.
The standard controls that can be validated are:
System.Web.UI.WebControls.DropDownList
System.Web.UI.WebControls.FileUpload
System.Web.UI.WebControls.ListBox
System.Web.UI.WebControls.RadioButtonList
System.Web.UI.WebControls.TextBox
System.Web.UI.HtmlControls.HtmlInputFile
System.Web.UI.HtmlControls.HtmlInputPassword
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlSelect
System.Web.UI.HtmlControls.HtmlTextArea

You don't need to set ControlToValidate property for CustomValidator when using it with CheckBox and simply use this in Server Validate like:
args.IsValid = cbVerify.Checked;

Related

How do I validate a selected value in a DropDownList?

I want the user to make a valid selection in a DropDownList, but I don't want to present any selection as the default so the default selected value is -- Select --. I am using a RegularExpressionValidator to only accept selected values that contain a literal comma (since the valid items are formatted LastName, FirstName).
However, I am perplexed as to how to get the validator to look for the Selected value! I'd really rather NOT make this a server-level validation, and if possible I'd like to keep it as simple as a Regex Validator.
Here's the code:
<asp:DropDownList ID="ddNames" runat="server">
</asp:DropDownList>
<asp:RegularExpressionValidator ID="RegexValidator" runat="server"
ControlToValidate="ddNames" ValidationExpression=".*\,.*"
ErrorMessage="Select a Valid User">
</asp:RegularExpressionValidator>
The dropdown values are:
-- Select --
Smith, John B
Jones, Bill
Wilkinson, Harmony
Hull, Cordell
Hill, Faith
Is there a way to aim the validator at the SelectedValue? As shown, the Validator seems not to be seeing any of the values in the control.
Am I right that you want to force the user to make a selection, and that selection should fit into your regex?
If so, you can easily add the RequiredFiledValidator class to your dropdown control, provide the InitialValue property to it equal to your -- Select -- item value so user will be forced to select something not equal to the -- Select --, and this value will be validated via RegularExpressionValidator control.
From MSDN:
Validation fails only if the value of the associated input control matches this InitialValue upon losing focus.
The strings in both the InitialValue property and the input control are trimmed to remove extra spaces before and after the string before validation is performed.
Validation succeeds if the input control is empty. If a value is required for the associated input control, use a RequiredFieldValidator control in addition to the RegularExpressionValidator control.
Also you should note for a RegularExpressionValidator class, that
Both server-side and client-side validation are performed unless the browser does not support client-side validation or client-side validation is explicitly disabled (by setting the EnableClientScript property to false).
So your code should be something like this:
<asp:DropDownList ID="ddNames" runat="server">
</asp:DropDownList>
<asp:RegularExpressionValidator ID="RegexValidator" runat="server"
ControlToValidate="ddNames" ValidationExpression=".*\,.*"
ErrorMessage="Select a Valid User" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="*" ControlToValidate="ddNames"
InitialValue="-- Select --" />
you can use RequiredFieldValidator.
<asp:DropDownList ID="ddNames" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please select" ControlToValidate="ddNames"
InitialValue="-- Select --"></asp:RequiredFieldValidator>

ASP.NET: skip running CompareValidator if some other field is not empty

My search form has 2 fields: Date and Object id. i'm using date validation like this:
<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
ErrorMessage="error msg" EnableClientScript="True"/>
ValueToCompare is set from code-behind (10 days back from now).
i don't want to run date validation, when Object id field is not empty (allows to search without date restrictions). What are solutions without using CustomValidator?
Simply set the 'Enabled' property to false in Code behind file. The Validation is performed after the Page.Load event but just before the event fires for the button or control that triggered the validation.
// Markup portion
<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
ErrorMessage="error msg" EnableClientScript="True"/>
// Code behind file
protected void Page_Load(object sender, EventArgs e)
{
if(!String.IsNullOrEmpty(ObjectId.Text))
{
cv.Enabled=false;
}
}
Now, when the Validation will be performed, CompareValidator will be skipped. You can also set the 'Visible' property to false as a second option. Check the MSDN here.
Check this.may be this help you:
if(!string.IsNullOrEmpty(Objectid.Text))
cv.ValueToCompare=DateTime.Now.AddDays(1);
else
cv.ValueToCompare=DateTime.Now.AddDays(-10);

Custom Validator not firing

I realize there are lots of similar posts, however I have not found one that has worked for me unfortunately. Basically, I have an asp:customvalidator that I am trying to add to a validationgroup with other validators so that all error messages appear in the same alert. Here is the customvalidator
<asp:TextBox runat="server" ID="txtVideo1Url" Columns="20" Width="98%" />
<asp:CustomValidator runat="server" ID="valURL1" ControlToValidate="txtVideo1Url" OnServerValidate="txtVideo1Url_ServerValidate" Display="None" ValidationGroup="submission" />
and here is the event
protected void txtVideo1Url_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = false;
valURL1.Text = "FAIL!";
}
The event isn't firing at all and I have no idea why. Once I can get the event firing I can put some actual logic into it, lol
UPDATE: I've noticed that I am now able to get the event firing, however the validationsummary is set to display all errors in a messagebox and this error isn't getting added to the messagebox.
Remember to set this property on the CustomValidator...
ValidateEmptyText="True"
You need to set the CausesValidation property of the TextBox to true, like this:
<asp:TextBox runat="server" ID="txtVideo1Url" Columns="20" Width="98%" CausesValidation="true" />
You will have to add ValidationGroup="submission" to the ASP.NET control that will fire the postback.
CustomValidators don't fire if other Validators in your ASPx are not validating. You may need to force a Page.Validate("something"), with your specific validation group. I suggest look at OnTextChanged event to force a page validate.

How to bypass validation for a button in ASP.NET?

I have an ASP.NET form that takes input from a user. There's a Submit button on the form and a button called Calc which does a calculation to populate a text field. The problem I'm having is that on the form I have a set of <ASP:REQUIREDFIELDVALIDATOR> validators and when the Calc button is pressed the form gets validated. I don't want the required fields to be validated when the Calc button is pressed, only the Submit button. Any way around this?
Set the CausesValidation property to false.
<asp:Button runat="Server" ... CausesValidation="False" />
Button.CausesValidation (If I remember correctly).
Try putting CausesValidation="false" as a button attribute.
Some sample code:
http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx
ASPX Page:
<asp:Button ID="buttonNew" runat="server" Text="New" CausesValidation="False" />
OR
CodeBehind Page: (.cs)
buttonNew.CausesValidation = false;
Check here to know more about Validated and Validating events for the controls.
Set the button.causesValidation to false.
this link
However, if all it is doing is calculating something based on user input then you shouldn't have it posting back at all. I would recommend using an HTML button and attach some javascript to it to do your work for you and then you won't have this problem.
While designing the button, you can set its property CausesValidation="false" to avoid validation on button click event. It does not allow to validation the server control and perform its click event only
You should use this
UseSubmitBehavior="False"
To disable validation in a specific control
Set the control's CausesValidation property to false.
<asp:Button id="Button3" runat="server"
Text="Cancel" CausesValidation="False">
</asp:Button>
To disable a validation control
Set the validation controls Enabled property to false.
To disable client-side validation
Set the validation controls EnableClientScript property to false.
For More Info

ASP.NET Custom Validator Client side & Server Side validation not firing

This has not happened to me before, but for some reason both the client and server side validation events are not being triggered:
<asp:TextBox ID="TextBoxDTownCity" runat="server" CssClass="contactfield" />
<asp:CustomValidator ID="CustomValidator2" runat="server" EnableClientScript="true"
ErrorMessage="Delivery Town or City required"
ClientValidationFunction="TextBoxDTownCityClient"
ControlToValidate="TextBoxDTownCity"
OnServerValidate="TextBoxDTownCity_Validate" Display="Dynamic" >
</asp:CustomValidator>
Server-side validation event:
protected void TextBoxDTownCity_Validate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Client-side validation event:
function TextBoxDCountyClient(sender, args) {
args.IsValid = false;
alert("test");
}
I thought at the least the Server Side validation would fire but no. this has never happened to me before. This has really got me stumped.
I looked at the output and ASP.NET is recognizing the client side function:
ASP.NET JavaScript output:
var ctl00_ctl00_content_content_CustomValidator2 = document.all ? document.all["ctl00_ctl00_content_content_CustomValidator2"] : document.getElementById("ctl00_ctl00_content_content_CustomValidator2");
ctl00_ctl00_content_content_CustomValidator2.controltovalidate = "ctl00_ctl00_content_content_TextBoxDTownCity";
ctl00_ctl00_content_content_CustomValidator2.errormessage = "Delivery Town or City required";
ctl00_ctl00_content_content_CustomValidator2.display = "Dynamic";
ctl00_ctl00_content_content_CustomValidator2.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_ctl00_content_content_CustomValidator2.clientvalidationfunction = "TextBoxDTownCityClient";
Rendered custom validator:
<span id="ctl00_ctl00_content_content_CustomValidator2" style="color:Red;display:none;">Delivery Town or City required</span>
Can any one shed some light as to why both client and server side validation would not be firing.
Edit: Typo I pasted in the wrong function, problem still the same
Just another update to the last comment: where by the TextBox cannot be empty. I tested this out and it is not true. On a blank page the CustomValidator fired my client side validation function fine without a value:
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="CustomValidator" ClientValidationFunction="TextBoxDAddress1Client"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Use this:
<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>
To validate an empty field.
You don't need to add 2 validators !
Your CustomValidator will only fire when the TextBox isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.
Note: If the input control is empty,
no validation functions are called and
validation succeeds. Use a
RequiredFieldValidator control to
require the user to enter data in the
input control.
EDIT:
If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.
So you can't do this...
<script>
function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />
But this works:
<script>
function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />
I'm guessing it conflicts with internal .NET Javascript?
Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via
Page.Validate({Insert validation group name here});
Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?
I'm not sure what else might cause this behavior.
Server-side validation won't fire if client-side validation is invalid, the postback is not send.
Don't you have some other validation that doesn't pass?
The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be
TextBoxDAddress1Client
(as you wrote)
Thanks for that info on the ControlToValidate LukeH!
What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.
Cheers!

Categories