Using custom validator

In my application there was a issue that I wanted to have single error displayed for phone number field where the phone number was collected using three separate fields.

Control validators in ASP.NET work on single control. Here there were 3 fields that needed one validator. So implementing custom validator was the only option.

here is the code…

<asp:CustomValidator ID=”rfvContactPhone” runat=”server” ClientValidationFunction=”ValidateRequiredFieldPhoneNumber”
Display=”Dynamic” ToolTip=”Please enter phone number”>
<img id=”imgContactPhone” runat=”server” src=”~/ImagesNew/ValidationErrorIcon.png” alt=”Please enter phone number”/>
</asp:CustomValidator>

  • Display Dynamic will ensure only error is displayed.
  • Image is embedded so that the error will look similar to DataErrorProvider.

JavaScript function

function ValidateRequiredFieldPhoneNumber(source, arguments)
{
if(document.getElementById(“ContactPhone_NPA”).value == “”)
{
arguments.IsValid = false;
}
if(document.getElementById(“ContactPhone_NXX”).value == “”)
{
arguments.IsValid = false;
}
if(document.getElementById(“ContactPhone_NNNN”).value == “”)
{
arguments.IsValid = false;
}
}

Only thing done here is to set the IsValid property of the control to false using the argument parameter of the validator function. Ensure the function signature and remember to use arguments parameter. That’s it.

Leave a comment