So I'm making a form which accepts a name, an age, and an Identification Card number.
The format of the IC number is yymmdd-xx-xxxx where the first four numbers are the D.O.B. of the person. The last four numbers are a unique code of the IC and the two numbers in between are state codes for where the person is born in. What I want to do is to take the first two numbers of the IC number (year person is born in), and deduct it with the current year, and compare that to the age the person gave and the output would say that the age is correct or incorrect.
Here is what I have tried so far.
function valForm() {
function valName() {
var regexName = /^[a-zA-Z]*$/;
if (regexName.test(document.ageVal.name.value)) {
return true;
} else {
return false;
}
}
function valIc() {
var regexIc = /^\d{6}-\d{2}-\d{4}$/;
if (regexIc.test(document.ageVal.icNum.value)) {
return true;
} else {
return false;
}
}
if (!valName()) {
alert("Enter a name using only alphabets");
document.ageVal.name.focus();
document.getElementById("notifName").innerHTML = "Alphabets only";
}
if (!valIc()) {
alert("Correct format is xxxxxx-xx-xxxx");
document.ageVal.icNum.focus();
document.getElementById("notifIc").innerHTML = "Not the correct format";
}
var today = new Date();
var year = today.getFullYear();
var yr = document.getElementById("icNum");
var yrIc = parseInt(yr, 10);
while (yrIc >= 100)
yrIc = Math.floor(yrIc / 10);
fullyrIc = 1900 + yrIc;
var actAge = year - fullyrIc;
var givnAge = document.getElementById("age");
if (actAge == givnAge)
document.getElementById("output").innerHTML = "Age is correct";
else
document.getElementById("output").innerHTML = "Age is not correct";
}
<form name="ageVal" action="javascript:valForm()">
<table border="solid" width="25%">
<tr>
<td>Name: </td>
<td colspan=2>
<input type="text" name="name" id="age">
<div id="notifName"></div>
</td>
</tr>
<tr>
<td>Age: </td>
<td colspan=2>
<input type="number" name="age" id="age">
<div id="notifAge"></div>
</td>
</tr>
<tr>
<td>IC: </td>
<td colspan=2>
<input type="text" name="icNum" id="icNum">
<div id="notifIc"></div>
</td>
</tr>
<tr>
<td colspan=3 align="center">
<input type="text" name="output" id="output" disabled>
</td>
</tr>
</table>
<input type="submit" form="ageVal" value="Submit">
</form>
I can't get any output after trying out a lot and making a lot of changes. I'm still new to JS and even newer to trying regex so I'm sure I'm doing a lot of things wrong here.
After some changes I can finally get an output thanks to the first two answers but the problem now is that the calculations are not correct. How should I correct it?