使用 Javascript 输入错误时更改边框颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26224761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing Border Color When Incorrect Input With Javascript
提问by dfsq
I'm working on a form that is supposed to validate the input in several textboxes when the user clicks the "submit" button. If any of the required boxes are left blank or have an incorrect type of input or format, the border of those textboxes is supposed to turn red and return to the normal color when the requirements are met.
我正在处理一个表单,当用户单击“提交”按钮时,该表单应该验证多个文本框中的输入。如果任何必需的框留空或输入类型或格式不正确,则这些文本框的边框应该在满足要求时变为红色并恢复正常颜色。
For example, a phone number is either supposed to be 7 or 10 digits long, if the user enters a six digit number like (123456), the border around this field should turn red, when the user enters one more number, like (1234567), the border should go back to it's regular color immediately, without the user having to click the "submit" button again.
例如,电话号码的长度应该是 7 位或 10 位,如果用户输入一个六位数字,如 (123456),则此字段周围的边框应变为红色,当用户再输入一个数字时,如 (1234567) ),边框应立即恢复正常颜色,用户无需再次单击“提交”按钮。
How my code is written, the border does turn red when the user enters too few numbers, however, the submit button must be clicked for the border to go back to its original color. Is there a way to change the color back without the button being clicked a second time?
我的代码是如何编写的,当用户输入的数字太少时,边框确实会变成红色,但是,必须单击提交按钮才能使边框恢复其原始颜色。有没有办法在没有第二次点击按钮的情况下改变颜色?
Here is my code:
这是我的代码:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validateForm() {
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
</html>
回答by Ivan Hanák
Once a user submits the form with invalid data, you can attach onkeyupevent listener into a input field, and everythime a user types something into the field, the form will be validated
一旦用户提交包含无效数据的表单,您可以将onkeyup事件侦听器附加到输入字段中,并且每次用户在该字段中输入内容时,表单都会被验证
document.getElementById("phone").onkeyup = validateForm;
I wrote once a user submits the formon purpose, since you do not want to fool your visitor by knowing that he typed only one character and he is getting validation error. (he is about to type 5 more characters)
我once a user submits the form是故意写的,因为您不想通过知道他只输入一个字符并且他收到验证错误来欺骗您的访问者。(他要再输入 5 个字符)
EDIT:
编辑:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
//at first, we define a variable stating that an event listener has been attached onto the field
var validatePhoneOnKeyUpAttached = false;
function validateForm() {
//then, we attach the event listened to the field after the submit, if it has not been done so far
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";//and you want to remove invalid style
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
回答by dfsq
You can simply add onkeyuphandler for input field:
您可以简单地onkeyup为输入字段添加处理程序:
<input type="text" id="phone" onkeyup="checkPhone()" />
and also make checkPhonefunction remove errorclass if input is valid:
如果输入有效,还可以使checkPhone函数删除error类:
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if (phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").className = '';
return true;
}
else if (phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").className = 'error';
return false;
}
}
Demo: http://jsfiddle.net/bcxLz4wh/
演示:http: //jsfiddle.net/bcxLz4wh/
回答by Dave
Use the blur event of your input like this:
像这样使用输入的模糊事件:
<input type="text" id="phone" onblur="validateForm();">
The blur event runs when you control loses the focus. If you need something more immediate you will need to use the keyup event.
当您的控件失去焦点时会运行模糊事件。如果您需要更直接的东西,您将需要使用 keyup 事件。

