ASP.NET Custom Validator Client side & Server Side validation not firing
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.
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?