In this article I will explain with an example, how to validate multiple validation groups with one Button in ASP.Net.
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing the user input.
RequiredFieldValidator – For validating TextBox.
The RequiredFieldValidator has been assigned with properties:
ControlToValidate – For providing validation property to the Control.
ValidationGroup – For specifying the groups.
Button – For validating the TextBoxes.
The
Button has been assigned with a
JavaScript OnClientClick event handler.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" ValidationGroup="Group1" runat="server"
ErrorMessage="TextBox1 is required." />
<br /><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="TextBox2" ValidationGroup="Group2" runat="server"
ErrorMessage="TextBox2 is required." />
<br /><br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="TextBox3" ValidationGroup="Group3" runat="server"
ErrorMessage="TextBox3 is required." />
<br /><br />
<asp:Button ID="btnValidate" runat="server" Text="Button" OnClientClick="return Validate()" />
Validating Multiple Validation Groups with one Button
When the
Button is clicked, the
JavaScript Validate function is called.
Inside the
JavaScript Validate function, first a variable is set to false and Group one is assigned to the variable using
Page_ClientValidate method.
Then, a check is performed if variable is true, it proceeds to perform validation on Group two using Page_ClientValidate and same for Group three.
Finally, the function returns the value of variable, which represents all the validation checks.
<script type="text/javascript">
function Validate() {
var isValid = false;
isValid = Page_ClientValidate('Group1');
if (isValid) {
isValid = Page_ClientValidate('Group2');
}
if (isValid) {
isValid = Page_ClientValidate('Group3');
}
return isValid;
}
</script>
Screenshot
Demo
Downloads