在 C# Visual Studio 中验证必填字段并确认字段
本文关键字:字段 确认 验证 Visual Studio | 更新日期: 2023-09-27 18:33:32
我在创建要求用户在字段中输入信息的表单时遇到问题,确认电子邮件和密码输入,并在匹配/填写所有这些字段后进入下一个表单。单独而言,我的代码是有效的,但我似乎找不到一种方法来制作它,以便在进入下一个表单之前满足所有要求。 目前,如果我单击继续按钮,它只会进入下一个表单。
我拥有的一些代码摘录是:
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
问题是无论 if 结果如何,都会创建和打开表单,因为它的代码在 ifs 之外。首先,检查没有字段为空,然后检查是否满足验证,然后打开新窗口。这样的事情应该有效:
//If both email and password are not empty
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
//if both email and password math the re entry
if (txtBoxEmail.Text == txtBoxConfirmEmail.Text &&
txtBoxPassword.Text == txtBoxConfirmPassword.Text)
{
//execute the code to open the new form
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}
}
if (! txtBoxEmail.Text.Equals( txtBoxConfirmEmail.Text))
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (! txtBoxPassword.Text.Equals( txtBoxConfirmPassword.Text))
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}
您是否在Visual Studio 2012中使用Web应用程序表单。您可以在 中使用 中的字段验证程序。要在表单提交之前验证的任何字段的 ASPX 文件。这比用 C# 编写所有内容要容易得多。
如果要将控件绑定或转换为数据对象,则可以使用 DataAnnotation。然后就很容易验证了。请参阅链接了解更多详情
http://msdn.microsoft.com/en-美国/图书馆/dd901590(VS.95).aspx
试试这个:
bool validationStatus = default(bool);
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
validationStatus = true;
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
validationStatus = true;
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
validationStatus = true;
}
if(!validationStatus)
{
Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}