【问题标题】:How validate many fields in code behind?如何验证代码中的许多字段?
【发布时间】:2014-01-27 10:05:28
【问题描述】:

我有一个注册页面,其中包含许多文件。其中许多应由用户填写。

我使用RequiredFieldValidatorRegularExpressionValidator 在客户端进行验证。 我应该在服务器端验证它们吗?如何?
我写了这段代码。我使用了很多 if 和 else if。它是否正确?

CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);

if (CaptchaControl1.UserValidated)
{
   if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
   {
       if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
       {
           try
           {
              // insert in database
           }
           catch (Exception)
           {
              lblMsg.Text = "Error";
           }
       }
       else if(RegEx.EmailValidate(txtEmail.Text) == 0)
       {
        EmailRegularExpression.Visible = true;
       }
       else if(RegEx.PasswordValidate(txtPass.Text) == 0)
       {
        passRegularExpression.Visible = true;
       }
       else if(RegEx.UserName(txtUserName.Text) == 0)
       {
        UnameRegularExpression.Visible = true;
        }
   }
   else if(txtFName.Text == string.Empty)
   {
    RequiredFieldValidator1.Visible = true;
   }
    // continue like above for another filed
}
else
{
    lblMsg.Text = "Please insert Secure Image";
}


并且:

public static int EmailValidate(string Mail)
{
    int i = 0;
    Regex regExEmail = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
    if (regExEmail.IsMatch(Mail))
        i = 1;
    return i;
}

【问题讨论】:

    标签: c# asp.net validation webforms


    【解决方案1】:

    我假设这是 Web 表单...

    验证会自动运行。您可以只使用Page.IsValid 属性:msdn

    您仍然需要手动检查验证码字段。

    CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
    
    if (CaptchaControl1.UserValidated && Page.IsValid)
    {
         // Insert in db.
    }
    

    【讨论】:

    • 是的,就是 Web 表单。谢谢。
    【解决方案2】:

    由于您使用了这些验证器,因此您不需要像您的代码一样再次在服务器端验证表单。

    但是你应该调用Page.Validate()然后用Page.IsValid方法检查页面。

    来自here

    example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      相关资源
      最近更新 更多