I have a rather large ASPX form with lots of textboxes and drop down lists to fill in. Most of the textboxes have RequiredFieldValidator controls and these work just fine.
However, I have 3 textboxes for Home, Mobile and Work Telephone numbers. Each textbox is optional but if it is filled in, then the value must be numeric. I don’t need to validate the format of the phone number at this point, only ensure that it is numeric.
The client side code for one of the fields looks like so:
<asp:Label ID="lblWorkPhone" runat="server" AssociatedControlID="txtWorkPhone" Text="<%$ Resources: Registration, WorkPhone %>" /><br />
<asp:TextBox ID="txtWorkPhone" runat="server" />
<asp:CustomValidator ID="validateWorkPhone" runat="server"
ValidationGroup="reg" ControlToValidate="txtWorkPhone" ForeColor="Red"
ErrorMessage="<%$ Resources: Registration, HomePhoneNumber %>"
Text="<%$ Resources: Registration, RequireMessage %>"
onservervalidate="validateWorkPhone_ServerValidate" />
The server side validation method is here :
protected void validateWorkPhone_ServerValidate(object source, ServerValidateEventArgs args)
{
long temp = 0;
long.TryParse(txtWorkPhone.Text, out temp);
if (temp == 0)
{
args.IsValid = false;
validateWorkPhone.IsValid = true;
}
else
{
args.IsValid = true;
validateWorkPhone.IsValid = false;
}
}
As far as I can tell the server side validation method is not firing at all. All the other validation controls on the page do seem to work fine.
Can anybody help?
Are the client-side validators (such as the RequiredFieldValidators) valid? The server-side validators only fire when all the client-side ones are valid.
EDIT
Most validators, such as RequiredFieldValidator or RegularExpressionValidator, perform the validation both client-side and server side. When the client-side validation fails, the submit is cancelled so a server-side-only validation doesn’t fire.
For a CustomValidator you will have to add a client-side validation explicitly, if you want that.