【问题标题】:How to identify and check Validation Controls in JavaScript?如何识别和检查 JavaScript 中的验证控件?
【发布时间】:2016-09-10 17:36:08
【问题描述】:

我有一个带有TextBox 元素的表单,每个元素都与RequiredFieldValidatorRegularExpressionValidator 或两者关联。每个验证控件都有SetFocusOnError="true"Display="None",但没有一个有ErrorMessage。这样,当验证器失败时,TextBox 会获得焦点,此时我必须找到 TextBox 并在 red 中突出显示它(以便用户看到错误)。

这是我的 JS:

$("input").change(function() {
    // Validate the whole page:
    Page_ClientValidate();

    if (Page_IsValid) {
        alert("Validation successful!");
    }
    else {
        // Loop thru each <input> and highlight them in red (.error) or green (.success):
        $("input").each(function() {
            // Get validator associated with $(this) input:
            var validator = ??? // using ControlToValidate maybe?

            if (validator has failed validation) ??? {
                $(this).addClass("error"); // $(this) -> current input
            }
            else {
                $(this).addClass("success");
            }
        }
    }
}

我不知道该怎么做是在???。同样,CSS 只是 .error {color:red}.success {color:green}

问题

1。 如何获取与当前输入关联的验证控件?

2。 如何检查验证器控件是否验证失败?

注意

  • 我想使用本机 ASP.NET 验证控件,而不是在客户端手动重写整个验证逻辑。所以EnableClientScript="False" 不是一个选项
  • 一切都在前端用 JavaScript 完成,而不是在代码隐藏文件中!同时,我可以使用&lt;%= %&gt;标签来访问ClientID

谢谢!

【问题讨论】:

    标签: javascript asp.net


    【解决方案1】:

    here的回答帮我解决了问题。基本上,我最终这样做了:

    var input = $(event.target);
    // Get validators based on this input's 'data-ctrl' attribute:
    var validators = $("." + input.attr("data-ctrl"));
    validators.each(function () {
         // RegExValidator does NOT fail on whitespace, so check that <input> is non-empty;
         // Don't have to do it on every single validator btw...
         if (!(this).isvalid || !input.val())
             input.removeClass("success").addClass("error");
         else
             input.removeClass("error").addClass("success");
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      相关资源
      最近更新 更多