HTML / JS验证

时间:2014-05-19 11:01:57

标签: javascript html

如何扩展javascript代码,以便考试编号最多只能输入4位数,用户不能再输入。另外,我如何扩展代码,以便不遗漏审查字段。对于单选按钮,我想添加一个验证,所以如果有人检查任何框,例如GCSE,会出现一条消息,说你已勾选(单选按钮勾选)  提前致谢

<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="name">Examination number</td>
<td><input type="text" name="Examination number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
<p> Please select <b>ONE</b> button.</br>
<input type="radio" name="group1" value="GCSE">GCSE<br>
<input type="radio" name="group1" value="AS" checked>AS<br>
<input type="radio" name="group1" value="A2" checked>A2<br>
</body>
</html>
<html>
<head>
<title>Success message</title>
</head>
<body>
<H1> You entered all the data required </H1>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

<input type="text" name="Examination number" maxlength="4"/> for maxlength

将此格式设置为onsubmit =&#34; return validateForm();&#34;

选中此项以获取javascript验证

http://www.w3schools.com/js/js_form_validation.asp

学习自己。

答案 1 :(得分:1)

您可以使用maxlength

<input type="text" id="test" name="test" maxlength="4"/>

或在JavaScript中,您可以这样做:

<强> Example

var input = document.getElementById("test");

input.oninput = function(){
    if (input.value.length > 4)
    {
        var str = input.value;
        str = str.substring(0, str.length - 1);
        input.value = str;
        alert("Some error message here");
    }
}