如何根据另一个字段的输入验证字段

时间:2012-11-06 16:25:53

标签: c# asp.net

我有2个字段,只有当另一个字段的内容为“NO”时,我才需要将其中一个字段设为必填字段。所以我在网上进行了研究,这就是我最终得到的结果。我唯一需要帮助的问题是代码的第一部分,它称之为:.getElementByID。我该如何构建呢?或者,如果你可以开启一些灯就会很棒。

<script>
        function Validate(source, args) {
                if (document.getElementById('<%= TextBox1.ClientID %>').value.toUpperCase() == "NO" &&
                document.getElementById('<%= TextBox2.ClientID %>').value.length == 0)
                        args.IsValid = false;
                else
                        args.IsValid = true;
        }
</script>
</head>
<body>
        <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="TextBox2 Should Be Filled"
                Display="Dynamic" ClientValidationFunction="Validate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        </form>
</body>
</html>

protected void Page_Load(object sender, EventArgs e)
        {
                if (!Page.IsPostBack)
                {
                        Page.Validate();
                        if (!Page.IsValid)
                                Response.Write("TextBox2 should be filled");

                }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
                args.IsValid = !(this.TextBox1.Text.Equals("NO", StringComparison.CurrentCultureIgnoreCase) && this.TextBox2.Text.Length == 0);

1 个答案:

答案 0 :(得分:4)

视线内的第一个错误是:

if (!Page.IsPostBack)  // <--- here
{
        Page.Validate();
        if (!Page.IsValid)
                Response.Write("TextBox2 should be filled");

}

!Page.IsPostBack更改为Page.IsPostBack,因为如果页面尚未发回,则验证用户输入是没有意义的。

根据您关于客户端验证码的问题:实际上是什么问题?您的代码是否有效,是否会出现异常,即使它无效也会回发?出了什么问题?

相关问题