gpt4 book ai didi

javascript - 验证表单中的年龄但没有得到输出,不确定什么是不正确的

转载 作者:行者123 更新时间:2023-11-28 18:42:08 25 4
gpt4 key购买 nike

因此,我正在制作一个接受姓名、年龄和身份证号码的表单。

IC 号码的格式为 yymmdd-xx-xxxx,其中前四个数字是出生日期。的人。最后四个数字是身份证的唯一代码,中间的两个数字是该人出生地的州代码。我想要做的是取身份证号码的前两个数字(出生年份) ),然后减去当前年份,并将其与该人给出的年龄进行比较,输出会表明该年龄是正确还是不正确。

这是我到目前为止所尝试过的。

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: &nbsp;</td>
<td colspan=2>
<input type="text" name="name" id="age">
<div id="notifName"></div>
</td>
</tr>

<tr>
<td>Age: &nbsp;</td>
<td colspan=2>
<input type="number" name="age" id="age">
<div id="notifAge"></div>
</td>
</tr>

<tr>
<td>IC: &nbsp;</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>

经过多次尝试并进行大量更改后,我无法获得任何输出。我对 JS 还很陌生,甚至对正则表达式也很陌生,所以我确信我在这里做错了很多事情。

经过一些更改,由于前两个答案,我终于可以得到输出,但现在的问题是计算不正确。我该如何纠正?

最佳答案

output id 元素是input 元素。使用 value 属性设置值而不是innerHTML来查看任何输出:

if (actAge == givnAge)
document.getElementById("output").value = "Age is correct";
else
document.getElementById("output").value = "Age is not correct";

JS Fiddle

关于javascript - 验证表单中的年龄但没有得到输出,不确定什么是不正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com