如何验证具有不同值的多个输入

How to validate multiple inputs with different values

本文关键字:输入 何验证 验证      更新时间:2023-09-26

我试图验证例如6个输入(I can create more than 100)这些输入是动态创建的,这里的问题是例如the first two input values must be between 0 and 10, then other two between 5 and 10 and the last two inputs between 3 and 5。我所做的是用IF验证这一点,但就像我说的,我可以创建100多个输入,这意味着很多代码,这是我所拥有的:

$(document).ready(function () {
  $('#create').change(function () {
    draw();
  });
  
  $('#btn').click(function () {
    validate();
  });
});
function draw() {
  var total = $('#create').val();
  var html = "";
  for (var x = 0; x < total; x++) {
    html += '<input id="InputNum' + x + '" />';
  }
  $('#draw').html(html);
}
function validate() {
  var Input1 = $('#InputNum0').val();
  var Input2 = $('#InputNum1').val();
  var Input3 = $('#InputNum2').val();
  var Input4 = $('#InputNum3').val();
  
  if (Input1 < 5 && Input1 >0 && Input2 < 5 && Input2 > 0)
    alert("Hello");
  else
    alert("Value must be between 0-5");
  
  if (Input3 < 15 && Input3 > 5 && Input4 < 15 && Input4 > 5 )
    alert("Hello");
  else
    alert("Value must be between 5-15");
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="create">
  <option selected disabled>Choose</option>
  <option>6</option>
<select />
  
  <div id="draw">
  </div>
  
  <button id="btn">Valida</button>

我想知道是否存在一种简单的方法来做到这一点,而不是使用if为我想要检查的每个输入?

使用eq()函数。

$("input").eq(-2) // before last element
$("input").eq(-1) // last element