我使用If语句来验证输入字段是否符合某些标准。在验证失败的情况下,将出现警告并将输入边框变为红色。
我如何确保只有验证失败的输入字段变为红色?我考虑将它们分为If和Else,但是,在两者都失败的情况下,这显然会执行其中一个操作。这让我相信If不是最适合这里,或者可能有一种方法在第一个If块中指定。
!如果(. getelementbyid("name" value。长度比;"30";||. getelementbyid("commentText" value。长度比;"100";) {. getelementbyid("name" .style。Border = "2px solid red";alert("名称必须少于30个字符");e.preventDefault ();} else {....
我更新了代码如下,然而,第一个if语句检查两个字段是否无效没有被执行…我不知道为什么?
更新代码:
if (
document.getElementById("name").value.length > 30 &&
document.getElementById("commentText").value.length > 100
) {
document.getElementById("name").style.border = "2px solid red";
document.getElementById("commentName").style.border = "2px solid red";
alert(
"Name must have fewer than 30 characters, and comment fewer than 100 characters"
);
event.preventDefault();
// document.getElementById("form").reset()
} else if (document.getElementById("name").value.length > 30) {
document.getElementById("name").style.border = "2px solid red";
alert("Name must have fewer than 30 characters");
event.preventDefault();
} else if (document.getElementById("commentText").value.length > 100) {
document.getElementById("commentText").style.border = "2px solid red";
alert("Comment must have fewer than 100 characters");
event.preventDefault();
} else {....
为什么不是两个单独的if
块?例如:
let isValid = true;
let errors = "";
if (document.getElementById("name").value.length > 30) {
isValid = false;
document.getElementById("name").style.border = "2px solid red";
errors += "Name must have fewer than 30 characters. ";
}
if (document.getElementById("commentText").value.length > 100) {
isValid = false;
document.getElementById("commentText").style.border = "2px solid red";
errors += "Comment must have fewer than 100 characters. ";
}
if (!isValid) {
e.preventDefault();
alert(errors);
} else {
//...
}
基本上检查每个字段并建立验证错误,然后在这些检查结束时响应总体失败的验证。
.length
返回的数据类型是number
而不是string
。同时更改比较号
if (
document.getElementById("name").value.length < 30 ||
document.getElementById("commentText").value.length < 100
) {
document.getElementById("name").style.border = "2px solid red";
alert("Name must have fewer than 30 characters");
e.preventDefault();
}
else{
//your stuff goes here
}
我将为commentText id添加另一个if字段
if (
document.getElementById("name").value.length > 30
) {
document.getElementById("name").style.border = "2px solid red";
alert("Name must have fewer than 30 characters");
e.preventDefault();
}
if (
document.getElementById("commentText").value.length > 100
) {
document.getElementById("commentText").style.border = "2px solid red";
alert("Comment must have fewer than 100 characters");
e.preventDefault();
}else {....