Invoke required field validator through javascript

Have a look at the client side api for ASP.Net validators. All the validators on the page are exposed in an Array via Page_Validators. You can call ValidatorValidate(validator) on a single validator to invoke it. So, to invoke all validators on the page you could:

Page_Validators.forEach(ValidatorValidate);

By the way, to use Array.forEach in older browsers you'll need to extend Array.


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>

Page_ClientValidate triggers validation for all validators on the form and as @gilly3 shows out you can also validate them all by looping the collection and calling ValidatorValidate(validator)

However if you want to validate just one particular validator then you need to call ValidatorValidate(validator) for just one item.

The validator argument needs to be a DOM object which can be tricky to get because the element ID might end up quite different than you specified in the mark up if you are using master pages or user controls.

e.g.

<asp:RequiredFieldValidator ID="rfvCampaignStartDate" runat="server" .../>

becomes

<span id="cph_0_rfvCampaignFile" ...>

I got around this in one of my projects by using a jQuery selector like this

ValidatorValidate($('[id$="rfvCampaignFile"]').get(0));

ASP.NET only prefixes the IDs to create a unique name I could use id$= part of the selector to match any IDs ending in "rfvCampaignFile" since I wrote the website I know it won't clash with other controls. Finally I use .get(0) to return the DOM object reference to the first (and only in my case) DOM object matched.