我无法获取此代码来验证文本的长度。
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {alert("The first name cannot be this long.");
return false;}
}
这是我的HTML代码
<html>
<head>
<meta charset = "utf-8">
<title> Contact Page </title>
<script type = "text/javascript" src = "contactform.js"> </script>
</head>
<body>
<h1> Contact Page </h1>
<form id = "contactform" action = "">
<p> Name: </p>
<label>
<input name = "firstname" type = "text" id = "firstname" onclick =
"validate()"/>
</label>
<p>
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Clear" />
</p>
</form>
<script type = "text/javascript" src = "contactform.js"> </script>
</body>
</html>
谁能告诉我我需要做什么?
答案 0 :(得分:1)
在return true;
函数的if
条件之外添加validate()
,然后在表单onsubmit
事件中使用它:
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {
alert("The first name cannot be this long.");
return false;
}
return true;
}
&#13;
<form id="contactform" onsubmit="return validate()">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" />
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>
&#13;
您还可以在该功能中添加更多验证。
答案 1 :(得分:0)
您可以使用以下正则表达式的pattern
属性:
.{1,15}
,设置输入内最多15个字符的限制。
注意:请务必使用required
属性,以防止用户在输入为空时提交表单。
<form id="contactform" action="">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" pattern=".{1,15}" required/>
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>