Search code examples
javascriptasp.netclientrequiredfieldvalidator

Invoke required field validator through javascript


I have a non standard submit button in my ASP.NET form along the lines of.

<a class="button" href="#" onclick="this.blur();SubmitForm();"><span>Submit</span></a>

Due to this, my required field validator is not being invoked on the client side. How can the required field validator be invoked through Javascript?

Alternatively is there a better way to accomplish what I am attempting to do?


Solution

  • You can use in built client side function named Page_ClientValidate for this.Check out the following code snippet for the reference

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientSide_Validation.aspx.cs"
        Inherits="ClientSide_Validation" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
            function performCheck() {
    
                if (Page_ClientValidate()) {
                }
    
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Label ID="lbl1" runat="server" Text="Please enter some value"></asp:Label>
            <asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="valReq" ControlToValidate="txtbox1" runat="server"
                ErrorMessage="*" Display="Dynamic">
            </asp:RequiredFieldValidator>
            <input type="button" id="btnValidate" value="Submit" onclick="performCheck()" />
            <a href="#" onclick="performCheck();">Validate</a>
        </div>
        </form>
    </body>
    </html>