0

我正在处理一个必须动态添加多个字段的页面。我基本上已经完成了这项工作,但我被验证所阻碍。
问题是表单字段需要特定的正则表达式验证,当只有一个输入时效果很好。现在,当 javascript 动态创建字段时,它只验证第一个字段。

我已经四处搜索,但没有找到任何东西,现在我唯一的想法是将正则表达式值从设置文件传递到 javascript 并在用户端验证它,但那时我将无法使用Page.IsValid()

所以我的问题是 - 是否可以将服务器端验证添加到由 javascript 动态创建的字段,以及如何?

谢谢!

4

2 回答 2

1

简短的回答是——这可能是可能的,但非常困难,而且解决方案非常脆弱,需要大量维护。

理论上,如果您可以在使用正则表达式验证器时找出 ASP.NET 生成的 JS 代码,然后对其进行逆向工程,您就可以做到这一点。这里的主要问题是新字段是在客户端而不是服务器端创建的。

如果您可以更新您的页面以便在服务器端动态创建新的文本框,那么您所要做的就是在 OnInit 方法中创建新的文本框和新的验证器,这将起作用。

这是它的样子。

protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        //set the appropriate conditions for your solution
        if (true)
        {
            //create text box
            TextBox txtNewField = new TextBox();
            txtNewField.ID = "txtNewField";

            //create and initialize validator
            RegularExpressionValidator regexR1 = new RegularExpressionValidator();

            regexR1.ValidationExpression = "set the regex here";
            regexR1.ControlToValidate = txtNewField.ID;
            regexR1.ErrorMessage = "you are doing something wrong";

            //add both of these to page wehre needed. 
            //I assume there is a panel control where you are adding these 
            //but you can customize it more
            pnlFields.Controls.Add(txtNewField);
            pnlFields.Controls.Add(regexR1);
        }
    }
于 2013-05-16T09:04:34.143 回答
0

如果您想要服务器端验证和客户端验证,那么您需要创建输入类型 =“文本”作为runat =“服务器”

示例:-

<input type="text" class="alphanum" id="txtName" name="txtName" runat="server" />

使用 Jquery 使用正则表达式进行验证

$("input.alphanum").bind("keyup", function(e) {
    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
于 2013-05-16T07:03:02.797 回答