[英]Email Validation in C#
這是我單擊按鈕時的代碼:
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" + textBox2.Text +"','" + textBox3.Text +"')";
int atpos = textBox3.Text.IndexOf("@");
int dotpos = textBox3.Text.LastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= textBox3.Text.Length)
{
MessageBox.Show("not a valid email address");
}
else
{
}
cmd.ExecuteNonQuery();
conn.Close();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
displayData();
MessageBox.Show("data inserted successfully");
}
我希望,如果條件為真,則不應將數據插入表中。
提前致謝。
不確定這是否是您要找的東西,但這里有:
private void button1_Click(object sender, EventArgs e)
{
int atpos = textBox3.Text.IndexOf("@");
int dotpos = textBox3.Text.LastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= textBox3.Text.Length)
{
MessageBox.Show("not a valid email address");
}
else
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" + textBox2.Text +"','" + textBox3.Text +"')";
cmd.ExecuteNonQuery();
conn.Close();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
displayData();
MessageBox.Show("data inserted successfully");
}
}
我建議您查看使用 Regex 來驗證電子郵件地址,她是如何在 c# 中使用 regex 進行電子郵件的鏈接: Regex Email validation
private void button1_Click(object sender, EventArgs e)
{
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(textBox3.Text);
if (match.Success)
{
MessageBox.Show("not a valid email address");
}
else
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('" + textBox1.Text+"','" + textBox2.Text +"','" + textBox3.Text +"')";
cmd.ExecuteNonQuery();
conn.Close();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
displayData();
MessageBox.Show("data inserted successfully");
}
}
此外,我不確定您的項目參數是什么,但我也建議使用某種 ORM。 如果您有興趣,請查看實體框架。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.