代码如下:<head>
<title>Exercise</title>
</head><body>
<div>
<h2>数据校验表单</h2>
<form method="post" name="register" action="#">
用户名:<input type="text" name="user" /><br />
密 码:<input type="password" name="pass" /><br />
电 邮:<input type="text" name="email" /><br />
<input type="submit" value="提交" /><br />
</form>
</div>
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
var check = function() {
var form = document.forms[0];
var errStr = "";
if (form.user.value == null || form.user.value.trim() == "") {
errStr += "\n用户名不能为空!";
form.user.focus();
}
if (form.pass.value == null || form.pass.value.trim() == "") {
errStr += "\n密码不能为空!";
form.pass.focus();
}
if (form.email.value == null || form.email.value.trim() == "") {
errStr += "\n电子邮件不能为空!";
form.email.focus();
}
if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(form.email.value.trim())) {
errStr += "\n电子邮件的格式不正确!";
form.email.focus();
}
if (errStr != "") {
alert(errStr);
return false;
}
}
document.form[0].onsubmit = check;
</script>
</body>用Chrome进行调试的时候,总是提示“Cannot read property '0' of undefined.”,不知道怎么回事?
这是来自《疯狂HTML5/CSS3/JavaScript讲义》上面的代码。
<title>Exercise</title>
</head><body>
<div>
<h2>数据校验表单</h2>
<form method="post" name="register" action="#">
用户名:<input type="text" name="user" /><br />
密 码:<input type="password" name="pass" /><br />
电 邮:<input type="text" name="email" /><br />
<input type="submit" value="提交" /><br />
</form>
</div>
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
var check = function() {
var form = document.forms[0];
var errStr = "";
if (form.user.value == null || form.user.value.trim() == "") {
errStr += "\n用户名不能为空!";
form.user.focus();
}
if (form.pass.value == null || form.pass.value.trim() == "") {
errStr += "\n密码不能为空!";
form.pass.focus();
}
if (form.email.value == null || form.email.value.trim() == "") {
errStr += "\n电子邮件不能为空!";
form.email.focus();
}
if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(form.email.value.trim())) {
errStr += "\n电子邮件的格式不正确!";
form.email.focus();
}
if (errStr != "") {
alert(errStr);
return false;
}
}
document.form[0].onsubmit = check;
</script>
</body>用Chrome进行调试的时候,总是提示“Cannot read property '0' of undefined.”,不知道怎么回事?
这是来自《疯狂HTML5/CSS3/JavaScript讲义》上面的代码。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货