[英]How do I get javascript validation on form input working?
Just trying to do a simple maximum length of fName
to not exceed over 10.只是试图做一个简单的fName
最大长度不超过 10。
I've been looking for online examples.我一直在寻找在线示例。 Can't find a common ground in anywhere on any examples I find.在我找到的任何示例中都找不到任何地方的共同点。
I'm able to submit anything except an empty text (because of required)我可以提交除空文本之外的任何内容(因为需要)
<head>
<script type="text/javascript">
var x = document.regoForm.fName.value;
if (x > 1)
{
alert( "too big" );
return false;
}
</script>
</head>
<body>
<form name="regoForm" id="regoForm" method="post">
</p>
<p>
<label for="fName">First Name</label>
<input type="text" required placeholder="John" name="fName"
id="fName"/>
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
您应该能够使用像maxlength
这样的内置方法
<input type="text" maxlength="10" required placeholder="John" name="fName" id="fName"/>
I've added an onclick handler to the button, and insert the code into a function.我已经向按钮添加了一个 onclick 处理程序,并将代码插入到一个函数中。
And if you want to check the length, not the value, then you should use the .length
to get the length of the text.如果你想检查长度,而不是值,那么你应该使用.length
来获取文本的长度。
Try this尝试这个
<head>
<script type="text/javascript">
function checkNameLength() {
if (document.getElementById('fName').value.length > 10) {
alert("too big");
return false;
}
}
</script>
</head>
<body>
<form name="regoForm" id="regoForm" method="post">
<p>
<label for="fName">First Name</label>
<input type="text" required placeholder="John" name="fName" id="fName"/>
</p>
<p>
<input type="submit" value="submit" id="submitBtn" onclick="return checkNameLength()">
</p>
</form>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.