C# 如果不正确,则使用正则表达式取消事件
我有一个c形式的正则表达式。我需要确定格式是否正确。如果正确,它将继续保存,但如果正确,它将显示其验证并取消保存事件 验证代码 保存代码C# 如果不正确,则使用正则表达式取消事件,c#,regex,winforms,C#,Regex,Winforms,我有一个c形式的正则表达式。我需要确定格式是否正确。如果正确,它将继续保存,但如果正确,它将显示其验证并取消保存事件 验证代码 保存代码 它声明它的格式不正确,但即使格式不正确,它仍会继续保存事件。我将它嵌套在函数中,以验证它是否为空。这似乎奏效了 private void emailTxt_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrWhiteSpace(emailTxt.Text))
它声明它的格式不正确,但即使格式不正确,它仍会继续保存事件。我将它嵌套在函数中,以验证它是否为空。这似乎奏效了
private void emailTxt_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrWhiteSpace(emailTxt.Text))
{
e.Cancel = true;
errorEmail.SetError(emailTxt, "Email is Empty!");
CancelBtn.Enabled = true;
}
else
{
string email = emailTxt.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
errorEmail.SetError(emailTxt, "Incorrect Format Try... email@email.com");
CancelBtn.Enabled = true;
return;
}
}
}
错误在别处,我们看不到。保存代码是什么?@GiorgiNakeuri我已经用我的保存代码更新了上面的代码。你能显示
validateChildren
method@Valentin以上是所有代码。@DonaldBury,这应该是ValidateChildren方法。你应该展示一下。
private void SaveBtn_Click(object sender, EventArgs e)
{
//SQL Connection and SQL for inserting a new admin
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
if (ValidateChildren(ValidationConstraints.Enabled))
{
try
{
string sql = "INSERT INTO Admin (Admin_Username, Admin_FName, Admin_SName, Admin_Email, Admin_Password) " + "VALUES (@adminName, @adminFirstname, @adminSurname, @adminEmail, @adminPassword);";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@adminName", usernameTxt.Text);
cmd.Parameters.AddWithValue("@adminFirstname", firstnameTxt.Text);
cmd.Parameters.AddWithValue("@adminSurname", surnameTxt.Text);
cmd.Parameters.AddWithValue("@adminEmail", emailTxt.Text);
cmd.Parameters.AddWithValue("@adminPassword", passwordTxt.Text);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Admin Successfully Added!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
con.Close();
}
private void emailTxt_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrWhiteSpace(emailTxt.Text))
{
e.Cancel = true;
errorEmail.SetError(emailTxt, "Email is Empty!");
CancelBtn.Enabled = true;
}
else
{
string email = emailTxt.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
errorEmail.SetError(emailTxt, "Incorrect Format Try... email@email.com");
CancelBtn.Enabled = true;
return;
}
}
}