主题:[讨论]如何判断所填写信息为合法的email格式
zone0356224
[专家分:0] 发布于 2007-01-27 17:06:00
我在学习用C#编写关于注册的代码,中间遇到了个难题就是如何判断所填写信息为合法的email格式,即存在@和.这两个符号,并写顺序正确,请问有人可以教教我么?
谢谢!!!![em1][em1][em1]
我用的是C#(ASP.NET)+SQL 2000.
做的是Winform的。
最后更新于:2007-01-27 17:12:00
回复列表 (共8个回复)
沙发
longlong16 [专家分:10670] 发布于 2007-01-27 18:44:00
建立regax对象 然后用正则表达式判断下就可以了!
板凳
zone0356224 [专家分:0] 发布于 2007-01-27 23:11:00
可以说的具体点么?
我是初学者,有些东西不懂,下面是我的代码:
private void submitButton_Click(object sender, System.EventArgs e)
{
if(userNameTextBox.Text.Length<3||userNameTextBox.Text.Length>12)
{
nameInformationLabel.ForeColor=Color.Red;
}
else
{
nameInformationLabel.ForeColor=Color.Black;
if(passwordTextBox.Text!=passwordAgainTextBox.Text||passwordTextBox.Text.Length<6||passwordAgainTextBox.Text.Length<6)
{
passwordAgainInformationLabel.Text="两次输入密码不一致或者过短!";
passwordAgainInformationLabel.ForeColor=Color.Red;
}
else
{
passwordAgainInformationLabel.Text="";
if(emailTextBox.Text.Length==0)
{
emailInformationLabel.Text="不能为空!";
emailInformationLabel.ForeColor=Color.Red;
}
else
{
emailInformationLabel.Text="";
SqlConnection conn=new SqlConnection("data source=A385A52FFF9B4DF;database=ForecastDB;uid=sa;pwd=");
SqlCommand myCommand=new SqlCommand();
string strsql = "select id,password from Customer where id='" + userNameTextBox.Text + "'";
SqlCommand cmd = new SqlCommand(strsql, conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
if(rd.Read())
{
conn.Close();
MessageBox.Show("用户名已存在!");
}
else
{
conn.Close();
//建立用户信息
myCommand.CommandText="Insert into Customer values('"+Convert.ToString(this.userNameTextBox.Text)+"','"+Convert.ToString(this.passwordTextBox.Text)+"','"+Convert.ToString(this.emailTextBox.Text)+"')";
myCommand.Connection =conn;
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("您已经注册成功!\n请登陆系统!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
User_loginForm form=new User_loginForm();
form.Show();
this.Hide();
}
}
}
}
}
emailTextBox是填写email的控件,请问如何改写代码才能使得程序可以判断所填写信息为合法的email格式?
谢谢!!
3 楼
zone0356224 [专家分:0] 发布于 2007-01-27 23:21:00
就是如果在emailTextBox控件里填写的信息中不包括"@"符号,就说明注册失败!!
4 楼
longlong16 [专家分:10670] 发布于 2007-02-12 10:33:00
你这又是何必呢?有自带的验证控件不用,干什么还要写一大堆!
5 楼
yl1207 [专家分:130] 发布于 2007-02-12 20:43:00
如果你用不来验证控件的话,只能自己写前太验证代码.
可以使用字符串比较,既字符串对象的Equals的方法.
提示:
string email=this.emailTextBox.Text.Trim();
if((email.Equals("@")==-1) || (email.Equals(".")==-1))
{
MessageBox.Show("Email格式不正确");
}
else
//其他验证代码
6 楼
sts017 [专家分:360] 发布于 2007-02-15 20:25:00
如果你是初学还是找本关于算法的东西好好学习学习
要不是的话,干脆就直接用里面的控件多好....只需要自己配置一下就行了
7 楼
jzyray [专家分:20610] 发布于 2007-02-16 00:15:00
Regex chk=new Regex(@"^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if(!chk.IsMatch(EmailAddress)){
throw new Exception("电子邮件地址不合法。");
}
8 楼
toicq2002 [专家分:180] 发布于 2007-04-02 17:19:00
其实你验证了也不一定是真的,还不如给注册者一点自由呢,也省自己的数据库,还能提高自己的速度,与人方便与已方便
我来回复