簡體   English   中英

2個字段上的ASP.NET自定義驗證器

[英]ASP.NET Custom Validator On 2 Fields

我知道我可以使用以下語法針對數據庫驗證txtfirstname字段,但是如果我需要進一步進行操作並針對數據庫驗證txtfirstname和txtlastname,我將進行哪些調整以僅在出現錯誤時出現錯誤?數據庫中已經存在兩個值嗎?

<asp:TextBox ID="txtfirstname" runat="server"></asp:TextBox><br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtfirstname"
        ErrorMessage="Please input a valid first name" Height="21px" OnServerValidate="CustomValidator1_ServerValidate"
        Width="154px">Please input first name</asp:CustomValidator><br />


protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;
    string fname = txtfirstname.Text;
    SqlConnection conn = new SqlConnection(strCon);

    SqlDataAdapter da = new SqlDataAdapter("select * from usertable where usertable.firstname=@fn", conn);
    da.SelectCommand.Parameters.Add("@fn");
    da.SelectCommand.Parameters["@fn"].Value = fname;
    DataSet ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
        args.IsValid = true;

} 

只需檢索“姓氏”字段的值,並執行與驗證名字相同的驗證:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = false;
        string fname = txtfirstname.Text;
        string lname = txtlastname.Text; // Get the last name
        SqlConnection conn = new SqlConnection(strCon);

        SqlDataAdapter da = new SqlDataAdapter("select * from usertable where usertable.firstname=@fn and usertable.lastname=@ln", conn); // Add last name to query
        da.SelectCommand.Parameters.Add("@fn");
        da.SelectCommand.Parameters["@fn"].Value = fname;
        da.SelectCommand.Parameters.Add("@ln"); // New parameter.
        da.SelectCommand.Parameters["@ln"].Value = lname;
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
            args.IsValid = true;

    }

請注意,我更新了您的代碼,並假定了姓氏字段的名稱。 請在您的代碼中對其進行測試,並根據需要根據需要對其進行更新。

另外,我建議您不要執行“選擇*”,因為這不是提高性能的好方法。 只需檢查一個字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM