ASP.NET CompareValidator 问题

发布于 2024-07-08 23:40:35 字数 238 浏览 5 评论 0原文

我有一个带有密码和确认密码文本框的网络表单。 我将 RegularExpressionValidator 附加到第一个,将 CompareValidator 附加到第二个。 现在的问题是,当我“密码”字段中有某些内容而“确认密码”字段中没有任何内容时,它不会显示字段不匹配的错误。 一旦我在确认密码字段中输入内容,它就会显示错误。 我还想允许将这两个字段留空。

我正在使用 .NET 2.0

它可能是什么?

I've got a web form with Password and Confirm Password text boxes. I've got a RegularExpressionValidator attached to the first one and CompareValidator to the second one.
Now the problem is when i have something in the Password field and nothing in Confirm Password field it does not display an error that fields don't match. As soon as i put something in the Confirm Password field it shows the error.
I also want to allow to leave both fields blank.

I'm using .NET 2.0

What might it be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

星光不落少年眉 2024-07-15 23:40:35

FWIW,如果您将密码框设置为 ControlToValidate,并将确认密码框设置为 ControlToCompare,那么它将起作用,因为密码框将包含一些内容,因此将运行验证。

当然,这可以允许他们提交带有空密码框和填写确认框的表单,因此在两者上放置所需的验证器可能是一个更好的主意。

FWIW, if you make the Password box the ControlToValidate, and the Confirm Password box the ControlToCompare, then it will work because the password box will have something in it and hence will run the validation.

Of course, this could allow them to submit a form with an empty Password box and a filled-in Confirm box, so putting a required validator on both is probably a better idea.

不知所踪 2024-07-15 23:40:35

我有同样的问题。 使用 CustomValidator 而不是 CompareValidator。 (CustomValidator 有一个名为 ValidateEmptyText 的有用属性,CompareValidator 缺少该属性,至少在 ASP.NET 2.0 中是这样。)

您需要编写适当的 ServerValidate 函数以及 ClientValidationFunction。 javascript 函数的函数签名与 ServerValidate 函数的函数签名基本相同:source(对象)、args(ServerValidateEventArgs)。

最棘手的部分是您需要编写自定义代码来访问“CompareTo”文本框,因为它不是 CustomValidator 的一部分。 我的字段位于 FormView 内; 您可能需要调整代码以适应您的特定情况。 在下面的代码中,“fv”是该 FormView 的名称。

客户端验证:

<script type="text/javascript">
<!--
  function cvPasswordRpt_Validate(source, args)
  {
    args.IsValid = (args.Value ==
                    document.getElementsByName("fv$tbPassword").item(0).value);
  }
//-->
</script>

ASPX 代码:

<label>New Password:</label>
<asp:TextBox ID="tbPassword" runat="server" CssClass="stdTextField" 
             TextMode="Password" ValidationGroup="edit" />
<br />
<label>Repeat New Password:</label>
<asp:TextBox ID="tbPasswordRpt" runat="server" CssClass="stdTextField"
             TextMode="Password" ValidationGroup="edit" />
<asp:CustomValidator ID="cvPasswordRpt" runat="server" Display="Dynamic"
             EnableClientScript="true" ValidationGroup="edit"
             ControlToValidate="tbPasswordRpt" ValidateEmptyText="true"
             ErrorMessage="Your passwords do not match."
             ClientValidationFunction="cvPasswordRpt_Validate"
             OnServerValidate="cvPasswordRpt_ServerValidate" />

服务器端验证 (VB.NET):

Protected Sub cvPasswordRpt_ServerValidate(ByVal sender As Object, 
                                           ByVal e As ServerValidateEventArgs)
  Dim _newPassword As String = DirectCast(fv.FindControl("tbPassword"), 
                                          TextBox).Text
  e.IsValid = e.Value.Equals(_newPassword)
End Sub

I had the exact same problem. Use a CustomValidator instead of the CompareValidator. (The CustomValidator has a helpful attribute called ValidateEmptyText, which the CompareValidator lacks, at least in ASP.NET 2.0.)

You will need to program an appropriate ServerValidate function, as well as the ClientValidationFunction. The function signature for the javascript function is basically the same as for the ServerValidate function: source (object), args (ServerValidateEventArgs).

The trickiest part is that you will need to write custom code to access the "CompareTo" textbox, since that's not part of the CustomValidator. My fields were within a FormView; you may need to adjust the code to fit your particular circumstances. In the code below, "fv" is the name of that FormView.

Client-side validation:

<script type="text/javascript">
<!--
  function cvPasswordRpt_Validate(source, args)
  {
    args.IsValid = (args.Value ==
                    document.getElementsByName("fv$tbPassword").item(0).value);
  }
//-->
</script>

ASPX Code:

<label>New Password:</label>
<asp:TextBox ID="tbPassword" runat="server" CssClass="stdTextField" 
             TextMode="Password" ValidationGroup="edit" />
<br />
<label>Repeat New Password:</label>
<asp:TextBox ID="tbPasswordRpt" runat="server" CssClass="stdTextField"
             TextMode="Password" ValidationGroup="edit" />
<asp:CustomValidator ID="cvPasswordRpt" runat="server" Display="Dynamic"
             EnableClientScript="true" ValidationGroup="edit"
             ControlToValidate="tbPasswordRpt" ValidateEmptyText="true"
             ErrorMessage="Your passwords do not match."
             ClientValidationFunction="cvPasswordRpt_Validate"
             OnServerValidate="cvPasswordRpt_ServerValidate" />

Server-side validation (VB.NET):

Protected Sub cvPasswordRpt_ServerValidate(ByVal sender As Object, 
                                           ByVal e As ServerValidateEventArgs)
  Dim _newPassword As String = DirectCast(fv.FindControl("tbPassword"), 
                                          TextBox).Text
  e.IsValid = e.Value.Equals(_newPassword)
End Sub
夏末染殇 2024-07-15 23:40:35

您还需要使用RequiredFieldValidator。 如果字段为空,很多验证控件都会通过,并且需要以这种方式与RequiredFieldValidator 配对。

You also need to use a RequiredFieldValidator. A lot of the validation controls will pass if the field is empty and need to be paired in this way with RequiredFieldValidator.

塔塔猫 2024-07-15 23:40:35

这个怎么样?

两个文本框字段 - txtEmail1(用于电子邮件地址)和 txtEmail2(用于确认)。

将 RegularExpressionValidator 附加到 txtEmail1 - 当空白时,它不会触发。 填充后,您的数据将得到验证。

将 CompareValidator 附加到 txtEmail1,将其数据与 txtEmail2 进行比较。 然后,将 CompareValidator 附加到 txtEmail2,将其数据与 txtEmail1 进行比较。

  • 当两个字段都为空时,三个验证器都不会触发。
  • 当填充 txtEmail1 时,它必须匹配正则表达式,并且它必须匹配 txtEmail2
  • 当填充 txtEmail2 时,它必须匹配 txtEmail1

这满足您的要求,即字段可以留空,但如果任一字段有数据,则会触发验证逻辑。

——乔

How about this?

Two TextBox fields - txtEmail1 (for email address) and txtEmail2 (for confirmation).

Attach a RegularExpressionValidator to txtEmail1 -- when blank, it won't fire. when populated, your data is validated.

Attach a CompareValidator to txtEmail1, comparing its data to txtEmail2. Then, attach a CompareValidator to txtEmail2, comparing its data to txtEmail1.

  • When both fields are blank, none of the three validators will fire.
  • When txtEmail1 is populated, it must match the regex, and it must match txtEmail2
  • When txtEmail2 is populated, it must match txtEmail1

This meets your requirement that the fields can be left blank, but fires the validation logic if either field has data.

-- joe

秋日私语 2024-07-15 23:40:35

CompareValidator、RegularExpressionValidator 和 RangeValidator 验证控件适用于非空字符串值。 这对于我们有一个非必填字段需要在输入时满足某些条件的情况很有用。

例如,我们有一个包含两个字段的表单:必须输入的主要电子邮件; 以及替代电子邮件,该电子邮件不是必需的,但在输入时必须进行验证。 为了验证这一点,我们将RequiredFieldValidator和RegularExpressionValidator添加到主电子邮件中,仅将RegularExpressionValidator添加到第二个字段。

如果在空输入上触发正则表达式验证器,那么验证上述表单将很困难,并且我们必须更改第二个正则表达式以允许空值,这相当难以做到和维护,而且不是那么明显的解决方案。

CompareValidator, RegularExpressionValidator and RangeValidator validation controls are working on non-empty string values. This is useful for situations where we have an non-required field that needs to satisfy some condition when entered.

For example we have a form with two fields: primary email that must be entered; and alternative email that is not required but when entered it must be validated. To validate this we would add RequiredFieldValidator and RegularExpressionValidator to the primary email and only RegularExpressionValidator to the second field.

It would be tricky to validate mentioned form if RegularExpressionValidator was triggered on empty input, and we would have to change the regex in the second one to allow empty value which is considerably harder to do and mantain and not so obvious solution.

或十年 2024-07-15 23:40:35

我遇到了同样的问题,并尝试了 patmortech 的答案,该答案有效,但导致比较验证器在用户输入确认文本框(使用客户端验证时)之前显示,因此不太完美。

相反,我创建了一个自定义验证器,仅当密码框中输入了某些内容时才进行比较。 下面的代码以防万一其他人在研究同一问题时遇到此问题有用。 根据您的要求,在密码框中使用此验证器(带或不带必填字段验证器)。

public class CompareIfRequiredPasswordValidator : BaseValidator
{
    private const string SCRIPTBLOCK = "UNIQUE1";

    private string controlToCompare;

    [Browsable(true)]
    [Category("Behavior")]
    [DefaultValue("")]
    [IDReferenceProperty]
    public string ControlToCompare
    {
        get { return controlToCompare; }
        set { controlToCompare = value; }
    }

    /// <summary>
    /// Server side validation function
    /// </summary>
    /// <returns></returns>
    protected override bool EvaluateIsValid()
    {
        TextBox txCompare = (TextBox)FindControl(ControlToValidate);
        TextBox txPassword = (TextBox)FindControl(ControlToCompare);
        if (txPassword.Text.Length == 0)
        {
            //No password entered so don't compare
            return true;
        }
        else
        {
            if (txCompare.Text == txPassword.Text)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (EnableClientScript) { this.ClientScript(); }

    }

    //Add the custom attribute here
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);
        if (this.RenderUplevel)
        {
            Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "controltocompare", base.GetControlRenderID(ControlToCompare));
        }
    }

    //Generate and register the script for client side validation
    private void ClientScript()
    {
        StringBuilder sb_Script = new StringBuilder();
        sb_Script.Append("<script language=\"javascript\">");
        sb_Script.Append("\r");
        sb_Script.Append("function pw_verify(sender) {");
        sb_Script.Append("\r");
        sb_Script.Append("var txCompare = document.getElementById(document.getElementById(sender.id).controltovalidate);");
        sb_Script.Append("\r");
        sb_Script.Append("var txPassword = document.getElementById(document.getElementById(sender.id).controltocompare);");
        sb_Script.Append("\r");
        sb_Script.Append("if (txPassword.value == '')");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return true;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("else");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("if (txCompare.value == txPassword.value)");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return true;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("else");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return false;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("</script>");
        Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK, sb_Script.ToString());
        Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "pw_verify");
    }
}

I had the same problem and tried patmortech's answer which worked but causes the compare validator to show before the user types in the confirm textbox (when using client side validation) so not quite perfect.

Instead I knocked up a custom validator that only does the comparison if the Password box has something entered in it. Code below just in case it is of use to anyone else who comes across this while looking into the same issue. Use this validator with or without a required field validator on the Password box according to your requirements.

public class CompareIfRequiredPasswordValidator : BaseValidator
{
    private const string SCRIPTBLOCK = "UNIQUE1";

    private string controlToCompare;

    [Browsable(true)]
    [Category("Behavior")]
    [DefaultValue("")]
    [IDReferenceProperty]
    public string ControlToCompare
    {
        get { return controlToCompare; }
        set { controlToCompare = value; }
    }

    /// <summary>
    /// Server side validation function
    /// </summary>
    /// <returns></returns>
    protected override bool EvaluateIsValid()
    {
        TextBox txCompare = (TextBox)FindControl(ControlToValidate);
        TextBox txPassword = (TextBox)FindControl(ControlToCompare);
        if (txPassword.Text.Length == 0)
        {
            //No password entered so don't compare
            return true;
        }
        else
        {
            if (txCompare.Text == txPassword.Text)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (EnableClientScript) { this.ClientScript(); }

    }

    //Add the custom attribute here
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);
        if (this.RenderUplevel)
        {
            Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "controltocompare", base.GetControlRenderID(ControlToCompare));
        }
    }

    //Generate and register the script for client side validation
    private void ClientScript()
    {
        StringBuilder sb_Script = new StringBuilder();
        sb_Script.Append("<script language=\"javascript\">");
        sb_Script.Append("\r");
        sb_Script.Append("function pw_verify(sender) {");
        sb_Script.Append("\r");
        sb_Script.Append("var txCompare = document.getElementById(document.getElementById(sender.id).controltovalidate);");
        sb_Script.Append("\r");
        sb_Script.Append("var txPassword = document.getElementById(document.getElementById(sender.id).controltocompare);");
        sb_Script.Append("\r");
        sb_Script.Append("if (txPassword.value == '')");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return true;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("else");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("if (txCompare.value == txPassword.value)");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return true;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("else");
        sb_Script.Append("\r");
        sb_Script.Append("{");
        sb_Script.Append("\r");
        sb_Script.Append("return false;");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("}");
        sb_Script.Append("\r");
        sb_Script.Append("</script>");
        Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK, sb_Script.ToString());
        Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "pw_verify");
    }
}
柠北森屋 2024-07-15 23:40:35

我尝试这样做:(由 patmortech 提供,非常感谢!)

FWIW,如果您将密码框设置为 ControlToValidate,并将确认密码框设置为 ControlToCompare,那么它将起作用,因为密码框将包含一些内容,因此将运行验证。

当然,这可以让他们提交一个带有空密码框和填写确认框的表单,因此在两者上放置所需的验证器可能是一个更好的主意。

为了避免留下空密码和填写的确认框,我只是在密码框中放置了另一个比较验证器,并交换了 ControlToValidate 和 ControlToCompare 值。

I tried to do this: (by patmortech, many thanks!)

FWIW, if you make the Password box the ControlToValidate, and the Confirm Password box the ControlToCompare, then it will work because the password box will have something in it and hence will run the validation.

Of course, this could allow them to submit a form with an empty Password box and a filled-in Confirm box, so putting a required validator on both is probably a better idea.

to avoid leaving empty password and filled-in confirm box, I just put another compare validator on Password box with ControlToValidate and ControlToCompare values swapped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文