Friday, November 27, 2009

ASP.NET Validation Controls - Conditionally validating

Using the server side Page.Validate() and Client Side Page_ClientValidate() , we can validate a group of controls conditionally. For eg. i just need to validate some fields only when a checkbox is checked. Both Page.Validate() and Page_ClientValidate() allows to pass a validation group , So we group a set of controls with a validation group and calls this validation functions in both client & server side only on the required validation condition

Server Side



protected void btnSubmit_Click(object sender, EventArgs e)
{
if(cbValidate.Checked)
{
//validate
Validate("vgSubmit");
}
if (!IsValid) return;
lblMsg.Text = "Passed validation";
}



ClientSide


function CheckValidation() {
var cbValidate = document.getElementById('<%=cbValidate.ClientID %>');
var flag = true;
if (cbValidate.checked) {
if (!Page_ClientValidate("vgSubmit"))
flag = false;
}
else {
Page_ClientValidate("vgDummy")
}
return flag;

}



Download Code