Thursday 19 March 2015

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

Here  I will explain how to solve the problem of RequiredFieldValidator not working when OnCientClick event is added to the Button in ASP.NET.

In order to make the RequiredFieldValidator work with OnClientClick we need to make use of Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly.

HTML Markup
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.
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>

Here first the Page_ClientValidate JavaScript function will make sure that all Validators have validated the form and the validation is successful then only it will raise the JavaScript confirmation.

How to use with Validation Groups
When using Validation Groups you need to simply pass the name of the Validation Group to the Page_ClientValidate JavaScript function and it will only verify the validations of the validators belonging to that group.
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate('ValidationGroupName')) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>

No comments:

Post a Comment