如何让我的验证在javascript中工作?

时间:2017-05-11 20:27:27

标签: javascript html

我无法获取此代码来验证文本的长度。

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>

谁能告诉我我需要做什么?

2 个答案:

答案 0 :(得分:1)

return true;函数的if条件之外添加validate(),然后在表单onsubmit事件中使用它:

&#13;
&#13;
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;
&#13;
&#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>