对文本字段和复选框进行验证

时间:2012-09-19 11:20:06

标签: javascript html

我可以向我的表格寻求帮助。我想要使​​文本字段和复选框都必填字段。复选框正在验证,我现在需要的是文本字段需要验证。我正在使用javascript。

HTML:

<form name="form" method="post" action="result.php" onSubmit="return checkme()">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Name: </td>
<td> <input name="Name" type="text" id="Name" size="20"></td>
</tr>
<tr>
<td>Email: </td>
<td> <input name="Email" type="text" id="Email" size="20"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> I agree to the terms</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit">      <input type="reset" name="reset" value="Clear"></td>
</tr>
</table>
</form>

使用Javascript:

<script language="JavaScript" type="text/JavaScript">
<!--//hide script
function checkme() {
missinginfo = "";
if (!document.form.agree.checked) {
missinginfo += "\n - You must agree to the terms";
}
if (missinginfo != "") {
missinginfo ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo + "\n__________________________________" +
"\nPlease complete and resubmit.";
alert(missinginfo);
return false;
}
else {
return true;
}
}

</script>

2 个答案:

答案 0 :(得分:0)

添加此JS代码以验证文本字段

if(document.form.Name.value==""){
missinginfo += "Required field";
}

同样适用于电子邮件字段。

答案 1 :(得分:0)

如果您将doctype转换为<!DOCTYPE html>,则可以使用

required="true"

将按以下方式实施

<input name="Name" type="text" id="Name" size="20" required="true">

大多数浏览器都支持HTML5。或者使用jQuery validation,它非常简单易用。

相关问题