Friday, 8 August 2014

ASP.Net RequiredFieldValidator not working when OnClientClick event is added to Button

ASP.Net RequiredFieldValidator not working when OnClientClick event is added to Button

 HTML

The HTML markup consists of an ASP.Net TextBox, a RequiredFieldValidator and a Button which has an OnClientClick event handler attached.

Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        return confirm('Do you want to submit data?');
    }
</script>
The Problem
The above code will display confirm and will not validate the TextBox using RequiredFieldValidator and the PostBack will happen even if the TextBox is left empty.
The Solution
Hence we need to make use of the Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly as shown below.

Solution HTML

Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate()) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>