简体   繁体   English

如果尚未填写控件,则不会触发自定义验证器

[英]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. 我有一个asp:文本框。 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. javascript验证不会触发。 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. 我不知道为什么验证器没有触发,如果文本框没有被触及。

Put the script below anywhere in your webform, and it will work the way you want: 将脚本放在webform中的任何位置,它将按您希望的方式工作:

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. Validator不能以您想要的方式本地工作,因为它将onchange事件处理程序附加到TextBoxes,因此,如果您根本不更改文本,则不会获得验证。

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. 但是如果强制所有TextBox都触发相同的事件onblur ,那么,无论你是否更改了文本,它都会触发验证,这就是上面的脚本正在做的事情:将该事件处理程序添加到所有的TextBox中。页面,并在发生时调用ValidatorOnChange函数。

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. 注意:如果您已经在应用程序中的每个WebForm中调用了任何脚本,并且希望此行为在任何地方都可以使用,则可以将代码添加到该脚本中(在其中的任何位置),并且解决方案将传播到所有你的网络表格。

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: 确保加载了jquery:

on global.asax: 在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. 在这两个更新后(我有一个提交btn)它运作良好。

SO, check if you load the unobstructed validation and that u're jquery is loaded. 所以,检查你是否加载了无阻碍的验证,并且你加载了jquery。

You have to call 你必须打电话

if (Page.IsValid) 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. RequiredFieldValidator在客户端上验证,这就是为什么这个工作正常。 However you should always validate on the server as well. 但是,您应该始终在服务器上进行验证。

For client side validation you have to write a JavaScript method doing the same. 对于客户端验证,您必须编写一个JavaScript方法。 You set the attribute in your CustomValidator: 您在CustomValidator中设置属性:

ClientValidationFunction="YourValidationMethod" 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;
}

我相信CustomValidators的设计旨在与RequiredFieldValidators分开操作,并且它们不会在空字段上触发是正常的。

Ahh, the joys of asp.net webforms :) 啊,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. 如果您正在使用其他控件,例如随其自身版本的jquery一起提供的radControls,这可能是一个问题,请确保通过禁用它们来使用框架附带的控件。

Alternatively you could turn off unobtrusive validation in the web.config and see if that makes it fire when it's empty. 或者,您可以在web.config中关闭不显眼的验证,看看是否在它为空时触发它。

 <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. 根据msdn文档......我对validateEmptyText = true属性的理解是,即使textbox为空,它也会触发自定义验证(validateName javascipt函数)。

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. 但我认为您可以通过使用必需的字段验证器和自定义验证器来解决您的问题,这是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM