Friday, July 15, 2011

Javascript -> Client Validations -> Refreshing Validation Summary Messages

Intro:
      Validation Summary is used to display the validation messages of all the web controls on the page at one place. Usually the validation summary doesn’t refresh the validation messages when each control is validated. So, some additional functionality should be added to force it display the updated validation messages

(1). Add a Validation Summary attribute on the aspx page as below…

<%-- This is Validation Summary on aspx page--%>
<asp:ValidationSummary runat="server" ID="valSummary"
HeaderText="* Please fill the below information correctly<br/><br/>"
DisplayMode="BulletList" ShowSummary="true" ValidationGroup="Submit" CssClass="star"
       EnableClientScript="true" />

(2). Add the Javascript function for refreshing the Validation Summary on the same page.

<script type="text/javascript" language="javascript">
//--This is the javascript for refreshing Validation Summary
function RecheckValidators() {
for (var i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], null, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(null);
}
</script>

 (3). Add the below code in code behind (aspx.cs file) on page load event to call the Javascript function on each control
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
//--Bind the javascript method to the onblur event of each control having validator
txtContactNumber.Attributes.Add("onBlur", "RecheckValidators('');");
txtEmailID.Attributes.Add("onBlur", "RecheckValidators('');");
.
.
.
  }
}

Javascript -> Client Validations -> Custom validator

Intro:
       Custom Validator is used to perform user-defined functionality check for the input data. The example scenario is shown in this post...

Validation Criteria: Date of birth should be minimum 18 years before the current year, that means the candidate appearing for the exam should be of 18 years or above.

(1) Add the input text field for DOB(i have used jquery calendar to  select the date).

<input type="text" runat="server" readonly="readonly" id="inputDOB" onkeydown="return false" />
<asp:CustomValidator runat="server" ID="custVal" ClientValidationFunction="validateDOB"ControlToValidate="inputDOB" Display="Dynamic" ErrorMessage="Age must be min.18 years"EnableClientScript="true" ValidationGroup="Submit"></asp:CustomValidator>


(2). Add the Javascript function to validate the DOB field


function validateDOB(source, arguments) {
 var txt = document.getElementById('<%=inputDOB.ClientID%>');
 
var dob = new Date(txt.value);
 
var currentDate = new Date();
 var yearDiff = currentDate.getFullYear() - dob.getFullYear();
 
if (yearDiff < 18) {
      arguments.IsValid = false;
 }
 else
      arguments.IsValid = true; 
}