The Page_ClientValidate(val)
method and the Page_IsValid
property are used for this task as shown below:
function performCheck()
{
Page_ClientValidate("DemoValidate");
if (Page_IsValid)
{
alert('Form Submitted Successfully');
return true;
}
else
{
alert('Please Correct The errors');
return false;
}
}
The above function can be called on page submission as shown below:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
ValidationGroup="DemoValidate" OnClientClick ="performCheck()" />
Note: The ValidationGroup
property should be the same for all the validation controls across the group which need to be validated.
Complete Source Code:
<h2>Client Side Validation Demo:</h2>
<script type ="text/javascript">
function performCheck()
{
Page_ClientValidate("DemoValidate");
if (Page_IsValid)
{
alert('Form Submitted Succesfully');
return true;
}
else
{
alert('Please Correct The errors');
return false;
}
}
</script>
<table>
<tr>
<td>EmployeeName:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter Employee Name" ValidationGroup="DemoValidate" ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>EmployeeID:</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Employee ID Cannot be Blank" ValidationGroup="DemoValidate" ControlToValidate="TextBox2">*</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage='"Please Enter 4-digit Employee ID' MaximumValue="4" MinimumValue="1" ValidationGroup="DemoValidate" ControlToValidate="TextBox2">*</asp:RangeValidator>
</td>
</tr>
<tr>
<td>EmailID:</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
<td>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please Enter Valid Email ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="DemoValidate" ControlToValidate="TextBox3">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Phoneno:</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox></td>
<td>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Phone no u have entered is not valid" ValidationExpression="\d{10}" ValidationGroup="DemoValidate" ControlToValidate="TextBox4">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="DemoValidate" OnClientClick ="performCheck()" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="DemoValidate" />