0

在 Page.Load 我动态添加一个标签,我应该验证的文本框和 customvalidator

Label myLabel3 = new Label();
                    myLabel3.ID = "lblEGN" + i.ToString();
                    myLabel3.Text = "EГН";
                    TextBox myTextBox3 = new TextBox();
                    myTextBox3.ID = "txtEGN" + i.ToString();
                    pnlPersonalCard.Controls.Add(myLabel3);
                    pnlPersonalCard.Controls.Add(new LiteralControl("<br />"));
                    CustomValidator cvEGN = new CustomValidator();
                    cvEGN.ID = "cvtxtEGN" + i.ToString();
                    cvEGN.ControlToValidate = "txtEGN" + i.ToString();
                   // cvEGN.ClientValidationFunction = "checkEgn";
                    cvEGN.ServerValidate += serverCheckEgn;
                    cvEGN.ErrorMessage = "Невалидно егн";
                    pnlPersonalCard.Controls.Add(cvEGN);


                    pnlPersonalCard.Controls.Add(myTextBox3);
                    pnlPersonalCard.Controls.Add(new LiteralControl("<br />"));

当然我提供了应该执行的自定义验证功能

protected void  serverCheckEgn(object sender,  ServerValidateEventArgs args) {
            string egn = args.Value;

            if (egn.Length != 10)
                args.IsValid = false;

            int year = Int32.Parse(egn.Substring(0, 2));
            int month = Int32.Parse(egn.Substring(2, 4));
            int day = Int32.Parse(egn.Substring(4, 6));

            if (month >= 40) {
                year += 2000;
                month -= 40;
            } else if (month >= 20) {
                year += 1800;
                month -= 20;
            } else {
                year += 1900;
            }


            string date = year + "/" + month + "/" + day;

            if (!CheckDate(date))
                args.IsValid=false;

            int checkSum = 0;
            int[] weights = new int[9] {2,4,8,5,10,9,7,3,6};

            for (var ii = 0; ii < weights.Length; ++ii) {
                checkSum += weights[ii] * Int32.Parse(egn.Substring(ii,1));
            }

            checkSum %= 11;
            checkSum %= 10;

            if (checkSum != Int32.Parse(egn.Substring(9,1)))
                args.IsValid=false;

            args.IsValid = true;
        }

但是当我按下我的按钮时,所有其他验证器(我有两个其他必填字段验证器和两个其他正则表达式验证器)正在工作,只有这个自定义验证器似乎我提供的功能没有执行!

4

3 回答 3

1

在将记录插入数据库期间检查 IsValid:

if (page.IsValid) 
{
    //insert record
}
else
{
    Response.Write("Input string is incorrect!");
}
于 2013-09-19T09:46:08.077 回答
0

当您尝试验证时,文本框的内容是否为空?要验证何时为空,您需要将ValidateEmptyText属性设置为true

于 2013-09-19T08:50:55.740 回答
0

伙计们,当我在文本框中写入时,您无法相信是什么导致了问题 - 5555

并且当程序到达这一行时

 int day = Int32.Parse(egn.Substring(4, 6));

我当然会得到一个例外,即我要减去的字符超出了我的字符串范围。

问题是另一个问题。即使在我的 button_click 函数中,我也得到了这一行

if (page.IsValid) 

在插入数据库之前检查一切是否正常;我不知道为什么,但记录被插入到数据库事件中虽然 args.IsValid=false

于 2013-09-19T09:35:16.867 回答