如果字符超过文本框,将最小值设置为2和最大为10个字符,则将其设置为红色BG



我有以下代码。我希望我的最大字符输入为10和分钟。但是我尝试过,当我输入的最小字符为2个或少于10个字符时,我的文本框仍然更改为红色。我在这里无法html最大长度或最低级。

此条件if (fname.value.match(/S/))检查文本框在应检查时是否不为空。我尝试使用 != "",但是当我输入某些内容时,它会跳过。

function validation() {
  var fname = "";
  var add = "";
  var message = "";
  // retrieving ids
  fname = document.getElementById('fname');
  add = document.getElementById('add');
  // white to red
  if (fname.value.match(/S/)) {
    fname.style.backgroundColor = "white";
  }
  if ((fname != '') || (fname.value >= 10 || fname.value <= 2)) {
    fname.style.backgroundColor = "red";
  }
  // white to red
  if (add.value.match(/S/)) {
    add.style.backgroundColor = "white";
  }
  if ((add != '') || (add.value >= 10 || add.value <= 2)) {
    add.style.backgroundColor = "red";
  }
  if (fname.value == "") {
    alert("Firstname is empty! Enter your firstname to resume");
    return false;
  }
  if (add.value == "") {
    alert("Address is empty! Enter your address to resume");
    return false;
  }
}
<form onsubmit="return validation()">
  Firstname:<br>
  <input type="text" name="fname" id="fname">
  <br> Address:
  <br>
  <input type="text" name="add" id="add">
  <br><br>
  <input type="submit" onClick="validation(); return false;" value="Submit">
</form>

您应该检查值的长度是否在2到10之间,而不是值本身。这样:

function validation() {
  var fname = document.getElementById('fname');
  var add = document.getElementById('add');
  
  if (2 <= fname.value.length && fname.value.length <= 10) { // if there is input between 2 and 10 characters, then set the background to white
    fname.style.backgroundColor = "white";
  }else {                                                    // otherwise, ...
    fname.style.backgroundColor = "red";
    alert("name is not valid!");
    return false;
  }
  
  
  if (2 <= add.value.length && add.value.length <= 10) {     // if there is input between 2 and 10 characters, then set the background to white
    add.style.backgroundColor = "white";
  }
  else {                                                     // otherwise, ...
    add.style.backgroundColor = "red";
    alert("addres is not valid!");
    return false;
  }
  
  return true;
}
<form onsubmit="return validation()">
  Firstname:<br>
  <input type="text" name="fname" id="fname">
  <br> Address:
  <br>
  <input type="text" name="add" id="add">
  <br><br>
  <input type="submit" onClick="validation(); return false;" value="Submit">
</form>

最新更新