Search code examples
asp.netvalidationclient-sideserver-side

Asp.NET. How to validate <asp:TextBox> control on a client side before submitting to server?


I have the following code on my asp.net page:

<table>
<tr>    
<td>
    <asp:DropDownList ID="ddlRegions" runat="server"></asp:DropDownList> 
</td>
<td>
    <label>Enter Iso:</label>
    <asp:TextBox ID="txtIso" runat="server" ></asp:TextBox>
    <asp:HiddenField ID="hfIso" runat="server" />
</td>
<td>
    <asp:CheckBox ID="chkActiveEmail" runat="server" Text="Email On/Off"/>
</td>
<td><asp:Button ID="btnAddActivation" Text="Add New Validation" OnCommand="AddNewActivation" runat="server"/></td>
</tr>     
</table>

I need to validate my textbox txtIso when my btnAddActivation button clicked and then I will need to proceed to the code-behind>

With simple html form I could use onsubmit = return Function(). How can I do it now?

Thank's


Solution

  • Custom javascript

    If you want to use custom javascript you can use the onclientclick:

     onclientclick="YourJSFunction()"
    

    The server side code will execute when you return true.

    <asp:Button ID="btnAddActivation" Text="Add New Validation" onclientclick="YouJSFunction()" OnCommand="AddNewActivation" runat="server"/>
    

    See here for more info:

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick(v=vs.110).aspx

    There are also built in validation controls that you could use for regular expression and required fields i.e.

    RegularExpressionValidator

    <asp:RegularExpressionValidator ControlToValidate="txtIso" runat="server"  ValidationExpression="String" />
    

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator(v=vs.110).aspx

    RequiredFieldValidator

     <asp:RequiredFieldValidator id="RequiredFieldValidator1"  
          ControlToValidate="txtIso"
          Text="Required Field!" 
          runat="server"/>
    

    http://msdn.microsoft.com/en-us/library/5hbw267h(v=vs.85).aspx