【问题标题】:javascript validation: comparing 2 text box valuesjavascript验证:比较2个文本框值
【发布时间】:2010-06-11 14:37:29
【问题描述】:

我有一个 5 行 2 列的表格。每个单元格都包含一个文本框。如果每列中的一个文本框为空,我想显示错误。我希望一行中的两个文本框都被填充或都为空。

我如何通过 Asp.net 验证控件做到这一点?

我想扩展 CompareValidator 以便它仅在 controlToValidate 和 controlToCompare 都包含一些文本或两者都为空时进行验证。

【问题讨论】:

  • 嗯,你想用javascript验证,还是用ASP.net验证..它们不太一样
  • 我想通过 Asp.net 验证来使用客户端验证。

标签: asp.net javascript validation


【解决方案1】:

您需要使用CustomValidator 并处理其ServerValidate 事件(以及可选的ClientValidationFunction 以进行客户端验证)。您可以在页面上执行一项并检查所有行,或者您可以每行执行一项并使用 ControlToValidate 属性为您提供正在验证的行的上下文。

客户端验证的任何示例都将取决于您的布局和您使用的任何 JavaScript 框架。它可能看起来像这样:

<table>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox11" /></td>
        <td><asp:TextBox runat="server" ID="TextBox12" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox21" /></td>
        <td><asp:TextBox runat="server" ID="TextBox22" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox31" /></td>
        <td><asp:TextBox runat="server" ID="TextBox32" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox41" /></td>
        <td><asp:TextBox runat="server" ID="TextBox42" /></td>
    </tr>
    <tr>
        <td><asp:TextBox runat="server" ID="TextBox51" /></td>
        <td><asp:TextBox runat="server" ID="TextBox52" /></td>
    </tr>
</table>
<asp:CustomValidator ID="TextBoxPairValidator" runat="server" ControlToValidate="TextBox11" ClientValidationFunction="TextBoxPairValidator_ClientValidate" />

<script type="text/javascript">
    (function () {
        window.TextBoxPairValidator_ClientValidate = function (sender, args) {
            var other = document.getElementById(sender.id.slice(0, -1) + '2');
            args.IsValid = (sender.value === '' && other.value === '')
                           || (sender.value !== '' && other.value !== '');
        };
    }());
</script>

该示例显然假设了一个相当简单的布局和相当静态的命名(即,如果您的控件位于命名容器中,您可能无法使用 ID 技巧从一个文本框转到另一个文本框)。希望这足以让您入门。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 2013-05-19
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多