Search code examples
asp.netgridviewrequiredfieldvalidator

How to place a required field validator inside a GridView TextBox


I have a GridView with some TemplateField items containing TextBox controls. I would like to add a required field validator on it. This is my code:

<asp:TemplateField HeaderText="vid">
    <EditItemTemplate>
         <asp:TextBox ID="txtvid" runat="server" Width="150px"
                            Text='<%# Bind("vid") %>'>
         </asp:TextBox>
    </EditItemTemplate>
    <ItemTemplate>
         <asp:Label 
                   ID="lblvid" runat="server" 
                   Text='<%# Bind("vid") %>'>
         </asp:Label>
    </ItemTemplate>
 </asp:TemplateField>

How do I place a required field validator on txtvid?


Solution

  • In the Edit template, add a RequiredFieldValidator like this:

    <EditItemTemplate>
        <asp:TextBox ID="txtvid" 
                     runat="server" Width="150px"
                     Text='<%# Bind("vid") %>'>
        </asp:TextBox>
        <asp:RequiredFieldValidator 
                     ControlToValidate="txtvid" 
                     runat="server" 
                     ErrorMessage="Please enter a 'vid' number" 
                     Text="*"/>
    </EditItemTemplate>
    

    Here is the reference for the RequiredFieldValidator on MSDN.

    UPDATE:

    If you wanted a regular expression validator, its pretty much the same, but with the RegularExpressionValidator control:

     <asp:RegularExpressionValidator 
         ControlToValidate="txtvid"
         ValidationExpression="\d{10}"
         runat="server" 
         ErrorMessage="Please enter a 'vid' of 10 digits" 
         Text="*"/>
    

    Here is a complete list of the functionality for the RegularExpressionValidator on MSDN.