Working with Validator

Introduction

In previous article we discussed how to use GridView to  fetch and display data from SQL Server Database, and how to insert/edit data item in it. But in most cases, we need to validate the user input either from client side or server side to prevent illegal data or SQL injection.  Following previous tutorial,  this article will discuss the following topics. 

    - Input validation using Required Field Validator, Regular Expression Validator , Custom Validator and Validation Summary

    - Custom Validatior OnServerValidate, ValidationGroup property. 

Background Knowledge

Validation Event in ASP.NET Page Life Cycle

When an ASP.NET Page runs, it goes through a series of processing stages. As a developer, you need to initialize, populate and bind events with your costumed control at a proper stage. Note that the validation events fire at Validation stage after the Page Load stage and before Postback Event Handling stage.


Using Validator



In this Gridview, we are going to add a RequiredField Validator for validate null value,  and a RegularExpression Validator to check valid format of StudentID.

Notice that CustomValidator has OnServerValidate and OnClientValidate property which allow you to implment server side/client side validation. 

In StudentID column,  add a RequiredField Validator and RegularExpression Validator for EditItemTemplate, On the footer add a RequriredField Validator, RegularExpression Validator and  a CustomValidator for checking duplicate primary key.

In StudentName column, add a RequiredField Validator for both EdiItemTemplate and Footer Template.


Web Form Page

<asp:gridview id="grdStudent1" runat="server" autogeneratecolumns="False" datakeynames="StudentID"
    showfooter="True" onrowediting="grdStudent1_RowEditing" onrowcancelingedit="grdStudent1_RowCancelingEdit"
    onrowupdating="grdStudent1_RowUpdating" onrowdeleting="grdStudent1_RowDeleting"
    onrowcommand="grdStudent1_RowCommand" onrowdatabound="grdStudent1_RowBound" cellpadding="4"
    forecolor="#333333" gridlines="None">
    <AlternatingRowStyle BackColor="White" />


    <Columns>


        <asp:CommandField ShowEditButton="True" />
                                                                                                                                                
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"> </asp:LinkButton>
            </ItemTemplate>
            <FooterTemplate>
                <asp:LinkButton ID="lnkInsert" runat="server"  ValidationGroup="InsertInfoGroup" CommandName="Insert" Text="Insert"></asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField> 
                                                                                                                                                                    
        <asp:TemplateField HeaderText="StudentID">
            <ItemTemplate>
                <asp:Label ID="lblStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox runat="server" ID="txtStudentID" Text='<%# Eval("StudentID") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtStudentID"
                    EnableViewState="False" ValidationExpression="^\d+$" Display="None" 
                    ErrorMessage='<%# string.Format("{0}{1}",grdStudent1.HeaderRow.Cells[2].Text, " is required") %> '>
                </asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="NumberValidator1" runat="server" ControlToValidate="txtStudentID"
                    EnableViewState="false" Display="None"  ValidationExpression="^\d+$"
                    ErrorMessage="Please input a valid format of number">                                                                                  
                </asp:RegularExpressionValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox runat="server" ID="txtNewStudentID" Text='<%# Eval("StudentID") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtNewStudentID"
                    ValidationGroup="InsertInfoGroup" Display="None" ErrorMessage="Student ID is Required"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="NumberValidator2" runat="server" ControlToValidate="txtNewStudentID"
                    ValidationExpression="^\d+$" ValidationGroup="InsertInfoGroup" ErrorMessage="Please input a valid format of number"
                    Display="None">                                                                                                                         
                </asp:RegularExpressionValidator>
                <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtNewStudentID"
                    OnServerValidate="HaveDuplicates" Display="None" ErrorMessage="StudentID already exist"
                    ValidationGroup="InsertInfoGroup" ValidateEmptyText="True" EnableClientScript="False">                                                  
                </asp:CustomValidator>
            </FooterTemplate>
        </asp:TemplateField>   
                                                                                                                       
        <asp:TemplateField HeaderText="StudentName">
            <ItemTemplate>
                <asp:Label ID="lblStudentName" runat="server" Text='<%# Eval("StudentName")  %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox runat="server" ID="txtStudentName" Text='<%# Eval("StudentName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtStudentName"
                    EnableViewState="false" Display="None" ErrorMessage="Student name is required"></asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox runat="server" ID="txtNewStudentName" Text='<%# Eval("StudentName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtNewStudentName"
                    EnableViewState="false" ValidationGroup="InsertInfoGroup" ErrorMessage="Student name is required"
                    Display="None"></asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>        
    </Columns>


</asp:gridview><pre name="code" class="html"><span style="font-family: Arial, Helvetica, sans-serif;">      </span>
 


Code Behind

protected void HaveDuplicates (object source, ServerValidateEventArgs args)
{
    string strSelect = "SELECT COUNT(*) FROM [StevensUniversity].[dbo].[Student] where StudentID = " +  args.Value.ToString();
    SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd = new SqlCommand(strSelect, con);
    //[Bug] rowsAffected value always -1 if using cmd.ExecuteNonQuery
    //int rowsAffected = cmd.ExecuteNonQuery();
    Int32 rowsAffected = (Int32)cmd.ExecuteScalar();
    con.Close();
    if (rowsAffected > 0)
    {
        args.IsValid = false;
    }
    else args.IsValid = true;
}
public void grdStudent1_RowCommand(object sender, GridViewCommandEventArgs e)
{
           
    if (e.CommandName.Equals("Insert"))
    {
        string NewStudentID = ((TextBox)grdStudent1.FooterRow.FindControl("txtNewStudentID")).Text;
        string NewDepartment = ((TextBox)grdStudent1.FooterRow.FindControl("txtNewDepartment")).Text;
        string NewStudentName = ((TextBox)grdStudent1.FooterRow.FindControl("txtNewStudentName")).Text;
        string NewGender = ((DropDownList)grdStudent1.FooterRow.FindControl("ddlNewGender")).SelectedItem.ToString().Trim();
        string NewEnrollmentDate = ((TextBox)grdStudent1.FooterRow.FindControl("txtNewEnrollmentDate")).Text;
        string strInsert = "Insert into Student (StudentID, Department, StudentName, Gender, EnrollmentDate) Values ('" 
                    + NewStudentID + "','" +  NewDepartment + "','"+  NewStudentName+ "','"+ NewGender+ "','" + NewEnrollmentDate + "')";

        if (Page.IsValid == true)
        {
            SqlConnection con = new SqlConnection(strCon);
            con.Open();
            SqlCommand cmd = new SqlCommand(strInsert, con);
            cmd.ExecuteNonQuery();
            con.Close();
            BindData();
        }  
    }    
}
public void grdStudent1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //string id = grdStudent1.DataKeys[e.RowIndex].Values[0].ToString();
    //[Bug]Null reference exception using following statement
    //string columnName = ((Label)grdStudent1.HeaderRow.FindControl("lblStudentID")).Text;
    bool  dataIsValid = false;
    string columnName = grdStudent1.HeaderRow.Cells[2].Text;     
    string StudentID = grdStudent1.DataKeys[e.RowIndex].Values[0].ToString();
    string NewStudentID = ((TextBox)grdStudent1.Rows[e.RowIndex].FindControl("txtStudentID")).Text;
    string NewDepartment =((TextBox)grdStudent1.Rows[e.RowIndex].FindControl("txtDepartment")).Text;
    string NewStudentName = ((TextBox)grdStudent1.Rows[e.RowIndex].FindControl("txtStudentName")).Text;
    string NewGender = ((DropDownList)grdStudent1.Rows[e.RowIndex].FindControl("ddlGender")).SelectedItem.ToString();
    string NewEnrollmentDate = ((TextBox)grdStudent1.Rows[e.RowIndex].FindControl("txtEnrollmentDate")).Text;
    string strUpdate = "Update Student set StudentID = '" + NewStudentID + "', Department='" + NewDepartment + "', StudentName='"                                                                              + NewStudentName  + "', Gender='" +  NewGender + "', EnrollmentDate='" + NewEnrollmentDate + "' where StudentID = " + StudentID;


    string strSelect = "SELECT COUNT(*) FROM [StevensUniversity].[dbo].[Student] where  StudentID = " + NewStudentID;
    SqlConnection con = new SqlConnection(strCon);
    con.Open();
    SqlCommand cmd1 = new SqlCommand(strSelect, con);
    Int32 rowsAffected = (Int32)cmd1.ExecuteScalar();      
    if (rowsAffected == 0) dataIsValid = true;
    if ((rowsAffected ==1) && (StudentID == NewStudentID)) dataIsValid = true;
    if (dataIsValid)
    {
        SqlCommand cmd2 = new SqlCommand(strUpdate, con);
        cmd2.ExecuteNonQuery();
        grdStudent1.EditIndex = -1;
        BindData();
    }
    else
    {
        CustomValidator err = new CustomValidator();
        err.IsValid = false;
        err.ErrorMessage  = "StudentID already exsit";
        Page.Validators.Add(err);
    }
    con.Close();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值