我正在开发一个表单,该表单应该在用户单击“提交”按钮时验证多个文本框中的输入。如果任何所需的框留空或输入类型或格式不正确,则这些文本框的边框应该变为红色,并在满足要求时恢复正常颜色。
例如,电话号码的长度应该是 7 位或 10 位,如果用户输入一个六位数字,例如 (123456),当用户再输入一个号码时,该字段周围的边框应该变为红色,像 (1234567),边框应该立即恢复为常规颜色,用户无需再次单击“提交”按钮。
我的代码是这样写的,当用户输入的数字太少时,边框确实会变成红色,但是,必须单击提交按钮才能使边框恢复到原来的颜色。有没有办法在不再次单击按钮的情况下将颜色改回原来的颜色?
这是我的代码:
<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>
最佳答案
一旦用户提交了包含无效数据的表单,您可以将 onkeyup
事件监听器附加到输入字段中,每次用户在该字段中输入内容时,表单都会被验证
document.getElementById("phone").onkeyup = validateForm;
我是故意写once a user submit the form
的,因为你不想通过知道他只输入了一个字符并且他得到验证错误来欺骗你的访问者。 (他即将再输入 5 个字符)
编辑:
<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>
关于javascript - 使用 Javascript 输入错误时更改边框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26224761/