如何验证动态文本框控件

How to Validate a dynamic Textbox control

我有一个动态创建的文本框(例如)

for(int i = 0; i < 4; i++)
{
    TextBox txtControl = new TextBox();
    txtControl.ID = "txt" + i;
    txtControl.AutoPostBack = true;
    txtControl.TextChanged += txtControl_TextChanged;
} 

我想验证文本框输入始终是一个整数,所以我生成了 TextChanged 事件处理程序,因为我有 CompareValidator 如下

void txtControl_TextChanged(object sender, EventArgs e)
{
    Log = new StringBuilder();
    CompareValidator validateTextBox = new CompareValidator();
    validateTextBox.Operator = ValidationCompareOperator.DataTypeCheck;
    validateTextBox.Type = ValidationDataType.Integer;
    validateTextBox.ControlToValidate = "txt1";
    string Message = validateTextBoxNumber.ErrorMessage;
 }

事件 txtControl_TextChanged 正在触发,但如果传递的是非整数,则不会抛出错误消息。

我的问题是

  1. 如何验证输入的是整数还是非整数
  2. 例子中我直接给了textbox id,怎么传 动态

现在因为你已经为这个问题标记了 jQuery,我有一个 jQuery 解决你的问题的方法。

我正在验证仅输入整数的文本框。

修改你后面的代码如下:

for(int i = 0; i < 4; i++)
{
    TextBox txtControl = new TextBox();
    txtControl.ID = "txt" + i;
    txtControl.cssClass = "validate"
} 

将以下脚本标记添加到您的前端:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".validate").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57 || e.which == 46)) {
                return false;
            }
        });
    });
</script>

Fiddle: http://jsfiddle.net/38nn3rdx/1/ 上面的函数不允许文本输入。

如果客户端验证就足够了,您可以使用 javascript 处理验证。或者在不使用 compareValidator.

的情况下进行如下服务器端验证
void txtControl_TextChanged(object sender, EventArgs e)
{
    TextBox txtBox = sender as  TextBox; 
    if(!string.IsNullOrEmpty(txtBox.Text) && txtBox.Text.All(Char.IsDigit))
    {
        //Throw error message
    }
}

更新:

由于txtControl_TextChanged是为每个动态TextBox注册的事件,当相应的事件发生时就会触发。因此,从 sender 我们可以轻松验证代码段中提到的文本框。即,TextBox txtBox = sender as TextBox;

你也可以使用自己的方法,类似的方法:

void txtControl_TextChanged(object sender, EventArgs e)
{
    Log = new StringBuilder();
    TextBox txtBox = sender as  TextBox; 
    CompareValidator validateTextBox = new CompareValidator();
    validateTextBox.Operator = ValidationCompareOperator.DataTypeCheck;
    validateTextBox.Type = ValidationDataType.Integer;
    validateTextBox.ControlToValidate = txtBox ;
    string Message = validateTextBoxNumber.ErrorMessage;
 }

请试试这个方法: 1) 在您的页面中编写下面的脚本函数,如下所示

$(".numeric").bind("keypress", function (event) {
        if (event.charCode != 0) {
            var regex = new RegExp("^[0-9]+$");
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
        }
    });

步骤 2) 为文本框添加 css class。喜欢

<input type="text" id="textboxid" class="numeric" />

所以这将只允许数值