用户名重复验证

时间:2012-07-27 09:28:37

标签: c# sql

我正在为论文做一个简单的登录页面,我已经完成了字符长度和密码不匹配验证。我的问题是我如何测试如果给定的用户名已存在于我的数据库 ....我正在使用C#进行编码,并将SQL管理工作室R2用于我的数据库......

private void add_Click(object sender, EventArgs e)
{
  string UserName = textBox1.Text;
  string Password = maskedTextBox1.Text;

  if (Password.Length <= MiN_LENGHT && UserName.Length <= MiN_LENGHT)
  {
    errorProvider1.SetError(textBox1, "User name must be at least 8 character");
    errorProvider2.SetError(maskedTextBox1, @"Password must be at least 8 character");

    maskedTextBox1.Clear();
    maskedTextBox2.Clear();
  }
  else if (maskedTextBox1.Text != maskedTextBox2.Text)
  {
    errorProvider1.SetError(maskedTextBox2, "Passwords don't match");

    maskedTextBox1.Clear();
    maskedTextBox2.Clear();
  }
  else if (textBox1.Text == "" || maskedTextBox1.Text == "" || 
           maskedTextBox2.Text == "")
  {
    MessageBox.Show("Please fill up the required records", "Information", 
                     MessageBoxButtons.OK, MessageBoxIcon.Warning);
  }
  else
  {
    x.da.InsertCommand = new SqlCommand(@"Insert into PlayerList 
                                         VALUES(@uname,@pw,@repw)", x.cs);
    x.da.InsertCommand.Parameters.Add("@uname", SqlDbType.NVarChar).Value =
                                         textBox1.Text;
    x.da.InsertCommand.Parameters.Add("@pw", SqlDbType.NVarChar).Value =  
                                         maskedTextBox1.Text;
    x.da.InsertCommand.Parameters.Add("@repw", SqlDbType.NVarChar).Value = 
                                         maskedTextBox2.Text;
    x.cs.Open();
    x.da.InsertCommand.ExecuteNonQuery();
    MessageBox.Show("Record Added", "Information", MessageBoxButtons.OK, 
                                         MessageBoxIcon.Information);
    button3.Enabled = true;
    x.da.SelectCommand = new SqlCommand( @"Select PlayerCode, uname from 
                                         PlayerList", x.cs);
    x.ds.Clear();
    x.da.Fill(x.ds);
    dataGridView1.DataSource = x.ds.Tables[0];
    x.cs.Close();
  }
}
希望你能帮忙......

4 个答案:

答案 0 :(得分:2)

您可以在数据库的用户名字段中添加UNIQUE CONSTRAINT或INDEX并捕获异常,也可以事先搜索它。我推荐第一种替代方案,因为它避免了竞争条件,但这不应该妨碍你进行搜索。

答案 1 :(得分:1)

在存储新用户之前,首先检查数据库中是否已存在该用户名,如果该用户不存在,则保存该记录。

如果该用户名确实存在,则跳过保存,并向用户显示他或她的用户名已被使用的友好消息

答案 2 :(得分:0)

您确定要在登录页面中进行验证吗?我认为这个验证是注册页面。

您可以通过两种方式进行此验证

1 - &GT;用户输入用户名后进行ajax调用,如果用户名已经存在,则显示重复消息。(用户将提供密码,这意味着用户时间将被保存)。

2 - &GT;在第二种方法中,您可以在服务器端完全进行验证。获取用户名并将其与现有用户名进行比较,并相应地显示消息。

答案 3 :(得分:-1)

关于用户名文本框的textchanged事件,您只需从数据库查询

 select username from user_mst where username='"+textusernm.text+"';

如果有,那么jst显示错误消息并禁用保存按钮 &安培;如果不是jst启用保存按钮并保存

相关问题