Friday, July 15, 2011

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; 
}

No comments:

Post a Comment