Articles → .NET → Invoke Different Validation Controls From A Single Button Using Validationgroup Property In Asp.Net

Invoke Different Validation Controls From A Single Button Using Validationgroup Property In Asp.Net





  1. Software requirement
  2. Prerequisite knowledge
  3. What is the purpose of ValidationGroup property in asp.net?
  4. Create a new project
  5. Add controls on the page
  6. Write a code to set the validationGroup of the button.
  7. Output

Software Requirement





Prerequisite Knowledge




  1. Basics about asp.net programming.
  2. How to create a project using visual studio?
  3. What are different server controls in asp.net?
  4. Basics about control’s events.
  5. What are validation controls in asp.net?

What Is The Purpose Of Validationgroup Property In Asp.Net?





Create A New Project




Picture showing the project structure of the sample project in visual studio
Click to Enlarge


Add Controls On The Page




Picture showing the different controls on the web page and their purpose
Click to Enlarge


Write A Code To Set The Validationgroup Of The Button




Name1:
<asp:TextBox ID="txtName1" runat="server"></asp:TextBox><asp:Button ID="btnTest" runat="server" Text="Button" /><br />
   Name2:
<asp:TextBox ID="txtName2" runat="server"></asp:TextBox><br /><asp:RequiredFieldValidator ID="rfvName1" runat="server" ValidationGroup="name1" ControlToValidate="txtName1" ErrorMessage="Please enter name1"></asp:RequiredFieldValidator><asp:RequiredFieldValidator ID="rfvName2" runat="server" ValidationGroup="name2" ControlToValidate="txtName2" ErrorMessage="Please enter name2"></asp:RequiredFieldValidator><br /><br /><br />
   Change Validation Group: 
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><asp:Button ID="btnChangeValidationGroup" runat="server" onclick="btnChangeValidationGroup_Click" Text="Change Validation Group" />




protected void Page_Load(object sender, EventArgs e) {
	if (!IsPostBack) btnTest.ValidationGroup = "name1";
}

protected void btnChangeValidationGroup_Click(object sender, EventArgs e) {
	if (!string.IsNullOrEmpty(TextBox1.Text)) 
    btnTest.ValidationGroup = TextBox1.Text;
}




  1. On page load we are assigning the ValidationGroup of button equal to the validation group of txtName1.
  2. On click of button (with caption ‘Change Validation Group’) we are changing the validation group of button depends upon what value is entered in the textbox.

Output




Picture showing the error message when first validation group is selected
Click to Enlarge



Picture showing the error message when second validation group is selected
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, February 8, 2013

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250