CompareValidator firing in Page_Load, validating empty control

E

Eric Maia

I have a textbox (StartDateTextBox) in a UserControl on my page, that
is supposed to have a date entered into it. I have a
RequiredFieldValidator that has its ControlToValidate property set to
the textbox. I also have a CompareValidator pointed to the textbox
with its Type="Date."

Despite all documentation to the contrary, I am getting an exception
when the page first loads that is thrown by the CompareValidator,
complaining that it cannot parse the empty string:

The value '' of the ValueToCompare property of 'StartDateValid' cannot
be converted to type 'Date'.

I am uncertain why this would be happening. I have composed the form
from a couple of user controls so I can reuse the same controls
separately on other pages. This UserControl has its set-up code
(determining which controls should be visible, the text of labels,
etc.) moved to a separate method which is called from Page_Load(). I
did this so the containing page can reset the control if it gets an
event from a different control.

Is the validation firing because the set-up code is not physically
within the Page_Load() method but is called from there? Even so, why
would the CompareValidator throw an exception instead of either
ignoring the empty value (which it is supposed to do) or setting its
IsValid property to false (which it should do if the value is in the
wrong format)?

Thanks - Eric
 
J

Jeffrey Palermo [MCP]

Eric,
It sounds like you are trying to use the CompareValidator to validate a
control against a value. The CompareValidator is intended to compare two
controls to each other to ensure that the default property is the same. Ex:
compare two textboxes to ensure a user has entered a password twice and that
the passwords match.

See http://www.w3schools.com/aspnet/control_comparevalidator.asp for some
examples of how to use the CompareValidator. Also check out the .Net
Framework SDK documentation for thorough documentation.

If you need to validate the value of a textbox to a value, then the
RangeValidator would be a good choice. Just set the beginning and end of
the range to be the same value.

If all you care about is that the value can be successfully parsed into a
DateTime object, then you'll have to perform a postback and try parsing the
value. You can do this with a CustomValidator and just write the server
side validation method. See
http://www.w3schools.com/aspnet/control_customvalidator.asp

Best regards,
Jeffrey Palermo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top