如何验证动态文本框控件

时间:2015-08-13 09:15:29

标签: c# asp.net validation dynamic

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

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. 在示例中,我直接给出了文本框ID,我该如何传递它 动态

3 个答案:

答案 0 :(得分:0)

现在,因为您已为此问题添加了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>

小提琴:http://jsfiddle.net/38nn3rdx/1/ 上述功能不允许文本输入。

答案 1 :(得分:0)

请尝试这种方式: 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类。像

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

所以这只允许数值

答案 2 :(得分:-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;
 }
相关问题