Sam Sam - 3 years ago 184
ASP.NET (C#) Question

Custom Validator not firing if control has not been filled in

I have a feeling this might be a very simple problem but cannot for the life of me figure it out.

I have a asp:textbox. I have a custom validator on which has client and server side validation.

Here is the code:

<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>

<asp:CustomValidator ID="vldFirstName" runat="server" ControlToValidate="txtFirstName"
ClientValidationFunction="ValidateName" OnServerValidate="vldFirstName_ServerValidate"
Text="Please put in your first name" ErrorMessage="First name missing"
ForeColor="Red" font-bold="true" Display="Dynamic"
ValidateEmptyText="true">
</asp:CustomValidator>


This will validate correctly on server side if I just go straight into my page and click submit, leaving the textbox blank.

However with client side validation. If I go into the box and come straight out of it without typing in anything. The javascript validation does not fire. If I then type something in. Leave the box. Go back and then clear the box the validation works. It comes back saying it is empty.

However I want it to as soon as they go into the box and leave it do the validation. I am not sure why the validator is not firing if the textbox has been untouched.

Answer Source

Put the script below anywhere in your webform, and it will work the way you want:

document.addEventListener('DOMContentLoaded', function() {
  [].forEach.call(document.querySelectorAll('input'), function(el, i) {
    el.addEventListener('blur', ValidatorOnChange);
  });
});

The Validator doesn't work natively the way you want, because it attachs an onchange event handler to the TextBoxes, so, if you don't change the text at all, you don't get the validation.

But if you force all the TextBoxes to trigger the same event onblur, then, whether if you have changed the text or not, it will trigger the validation, and that's what the script above is doing: adding that event handler to all the TextBoxes in the page, and calling the ValidatorOnChange function when it occurs.

Note: if you already have any script that is called into every WebForm you have in your application, and you want this behavior to work everywhere, you can add the code into that script (anywhere inside it), and the solution will propagate to all your webforms.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download