Okay, if you have two text inputs on a page, the first being the IC input and the second being the age:
1) Add the following to the end of template.js:
function icToAge() {
// A listener on the first input
$('input.text:eq(0)').bind('input propertychange', function() {
// Define the IC number format yymmdd-##-####
var patternMatch = /^[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])-[0-9]{2}-[0-9]{4}$/;
var icInput = $(this).val();
if (patternMatch.test(icInput) != true) {
// Invalid IC number format
$('input.text:eq(1)').val('No age available.');
}
else {
var d = new Date();
var todayYear = d.getFullYear();
var todayShortYear = String(todayYear).substr(2,2);
var todayMonth = d.getMonth()+1;
var todayDate = d.getDate();
var birthDateCode = icInput.split('-')[0];
var birthYear = birthDateCode.substr(0,2);
var birthMonth = birthDateCode.substr(2,2);
var birthDate = birthDateCode.substr(4,2);
if(birthYear > todayShortYear) {
birthYear = 19+birthYear;
}
else {
birthYear = 20+birthYear;
}
var age = todayYear - birthYear;
if ( todayMonth < birthMonth) {
age--;
}
else if ((birthMonth == todayMonth) && (todayDate < birthDate)) {
age--;
}
// Load the age into the second input
$('input.text:eq(1)').val(age);
}
});
}
2) Add this to the source of the IC input question to call the
icToAge() function:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
icToAge();
});
</script>
Some notes:
- The
icToAge() function validates an IC input against a regular expression and if it passes, the current age is calculated and inserted in the next text input.
- This code is designed for a page where the IC input is the first text input and the age is the second.
- The function resides in template.js because Expression Manager destroys valid regular expressions if placed in the question source.
- The validation regex could probably use some tuning for 30-day-months, etc - I just did it quickly for this example.