. net验证动态创建的字段

.NET validate dynamically created fields

本文关键字:字段 创建 动态 验证 net      更新时间:2023-09-26

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

我已经搜索了,但没有发现任何东西,现在我唯一的想法是将regex值从设置文件传递到javascript并在用户端验证它,但我将无法使用Page.IsValid()

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

谢谢!

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

理论上,如果你能弄清楚ASP生成的JS代码,你可以这样做。. NET使用正则表达式验证器时,然后对其进行反向工程。这里的主要问题是新字段是在客户端创建的,而不是在服务器端。

如果你可以更新你的页面,以便在服务器端动态创建新的文本框,那么你所要做的就是在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);
        }
    }

如果您想要服务器端验证和客户端验证,那么您需要创建Input type="text"作为runat =" Server "

: -

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

使用Jquery验证Regex

$("input.alphanum").bind("keyup", function(e) {
    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});