最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Custom Validator not firing if control has not been filled in - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Sep 16, 2015 at 12:12 stuartd 73.3k16 gold badges138 silver badges168 bronze badges asked Sep 16, 2015 at 12:10 SamSam 9483 gold badges13 silver badges32 bronze badges 10
  • 2 It might help to see the ValidateName code. – stuartd Commented Sep 16, 2015 at 12:12
  • @stuartd, validation code is just simple at the moment checking the length if it is greater than 3 and value is not null. I have debugged it and put a breakpoint everytime the code is called client side. Works fine when I have put something in and then deleted it. But does fire if it has just been skipped through – Sam Commented Sep 16, 2015 at 12:14
  • What does the ValidateName say the input value is when skipped and when put/delete? – Asons Commented Sep 22, 2015 at 9:34
  • Does the validation function definitely have the correct function parameters defined on ValidateName (sender, args)? Do you need to change the appsetting for UnobstrusiveValidationMode? – Jono_2007 Commented Sep 22, 2015 at 9:55
  • @Sam I have tested your code, everything works fine in my test application. it would be better if you could share validateName Code with us, may there is something wrong in that code or any other dependent control causing this issue. – BASEER HAIDER JAFRI Commented Sep 22, 2015 at 10:19
 |  Show 5 more comments

6 Answers 6

Reset to default 4 +50

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.

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.

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.

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>

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.

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;
}
发布评论

评论列表(0)

  1. 暂无评论