Sam
Sam

Reputation: 948

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.

Upvotes: 12

Views: 3183

Answers (6)

Manraj
Manraj

Reputation: 494

You have to call

if (Page.IsValid)

on postback on the server, otherwise your server validation will not be called. The RequiredFieldValidator validates on the client, that's why this one is working. However you should always validate on the server as well.

For client side validation you have to write a JavaScript method doing the same. You set the attribute in your CustomValidator:

ClientValidationFunction="YourValidationMethod"

and the method does something like this

function YourValidationMethod(source, args)
{

   if (valid) // do check here
     args.IsValid = true;
  else
     args.IsValid = false;
}

Upvotes: 2

Buzinas
Buzinas

Reputation: 11725

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.

Upvotes: 4

Viru
Viru

Reputation: 2246

As per the msdn docs...what I uderstand about the validateEmptyText = true property is it will trigger the custom validation (validateName javascipt function) even though textbox is empty.

May be on on first load value is undefined for that textbox but when you edit and undo it value of textbox will be now empty.(not undefined) that is why it fires when you edit and undo but not on first load.

one way is to intialize textbox value with empty string on load event of form

but I think you can solve your problem by using required field validator with custom validator which is better approach.

Upvotes: 2

Eric Kelly
Eric Kelly

Reputation: 452

Ahh, the joys of asp.net webforms :)

If you are using other controls, such as radControls that ship with their own version of jquery, that could be one issue, make sure to use the one shipped with the framework by disabling theirs.

Alternatively you could turn off unobtrusive validation in the web.config and see if that makes it fire when it's empty.

 <appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Upvotes: 2

Paul Kienitz
Paul Kienitz

Reputation: 878

I believe that CustomValidators are by design intended to act separately from RequiredFieldValidators, and it is normal for them not to fire on empty fields.

Upvotes: 3

Ziv Weissman
Ziv Weissman

Reputation: 4516

I've tested that code, with random client validation, and validation didn't fire properly.

I've added the unobstructed elements:

  1. On page load: (or however you want to activate it)

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.UnobtrusiveValidationMode = UnobtrusiveValidationMode.WebForms;
    }
    
  2. Make sure jquery is loaded:

on global.asax:

 protected void Application_Start(object sender, EventArgs e)
        {
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
            new ScriptResourceDefinition
        {
          Path = "~/scripts/jquery-2.1.4.min.js",
          DebugPath = "~/scripts/jquery-2.1.4.js",
          CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.0.min.js",
          CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.0.js"
        });
        }

After these two were updated (and I have a submit btn) It worked well.

SO, check if you load the unobstructed validation and that u're jquery is loaded.

Upvotes: 2

Related Questions