将文本框验证到数据库LIKE LOGIN FORMS中的表的列

时间:2013-12-06 09:26:01

标签: c# asp.net sql validation

如何验证文本框输入的值在拍摄或运行q查询之前是否有效?你知道像电子邮件或登录或注册表格,它可以检查数据库中是否存在电子邮件。你如何在ASP.NET中做到这一点?

http://msdn.microsoft.com/en-us/library/s5z00s5e

这是我发现的最近的教程!!但我真的没有得到它。所以任何人都可以帮助我吗?

代表:

我有一个文本框(txt_checkemail)

一个名为(employees)的表,其中包含列(用户名),文本框必须验证插入的电子邮件是否在列用户名内退出。

请帮忙!!

2 个答案:

答案 0 :(得分:1)

您可以使用此活动:

private void txt_checkemail_TextChanged(object sender, EventArgs e)
{
   var isValid = ValidateEmail(txt_checkemail.Text);

   if (isValid)
   {
       MessageBox.Show("The emailadress you've entered is valid!");
   }
   else
   {
       MessageBox.Show("The emailadress you've entered is NOT valid!");
   }
}

private bool ValidateEmail(object valueToCheck)
{
    //execute query on the database to check if the value entered in the textbox is valid.
}

或者你可以使用一个按钮,如果你点击它,它将检查文本框中输入的值是否有效。

答案 1 :(得分:1)

您应该使用CustomValidator控件。

表单代码

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
        runat="server" ErrorMessage="CustomValidator" 
            onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

代码背后

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (ValidateEmail(txtEmail.Text))
            args.IsValid = true; 
        else
            args.IsValid = false;
    }

protected void Button1_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
        //Carry on
    else
       //Validator has failed, ask user to correct.
}