如何设置输入的数据最小值和设置消息,如果值小于最小值

How to set data-min of input and set message if value is less than min value

本文关键字:设置 最小值 消息 如果 小于 何设置 输入 数据      更新时间:2023-09-26

我试图设置输入的最小值,但消息不显示。如果需要输入并且输入的值小于最小值,如何显示此消息。我的代码是:

$(".mydiv :input").each(function () {
   var min = $(this).attr('datamin');
   if(min !== undefined && min !== null && min !== false) {
   if(value < min) {
      valid = false;
      $(this).addClass('error');
      $(this).closest('label').addClass('red');
      $(this).closest('label').html('Required min value:' + min);
   } else {
      $(this).removeClass('error');
      $(this).closest('label').removeClass('red');
   }
}
 <input datamin='1' class="required" name="order"/>
 <label for="order"><?php echo __('order'); ?><span class="red">*</span><span class="min_value" style="display:none"></span></label>

您需要将此附加到change事件,而不是在每个事件上执行。您还需要设置值(使用.val())

转换和围绕值的更多验证也会很好(使用isNaN)

$(document).ready(function() {
  $(".mydiv input").on('change', function() {
    var min = Number($(this).attr('datamin'));
    var value = Number($(this).val());
    if (min !== undefined && min !== null && min !== false && !isNaN(min)) {
      if (value < min || isNaN(value)) {
        valid = false;
        $(this).addClass('error');
        $(this).closest('label').addClass('red');
        $(this).closest('label').html('Required min value:' + min);
      } else {
        $(this).removeClass('error');
        $(this).closest('label').removeClass('red');
      }
    }
  })
});
.error, .red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">
  <input datamin='1' class="required" name="order" />
  <label for="order">
    <?php echo __( 'order'); ?><span class="red">*</span><span class="min_value" style="display:none"></span>
  </label>
</div>

您需要实际检索值:

var theValue = +$(this).val(); //you're not doing this
//note that + sign attempts to coerce a value (vs. text), but you may try some additional validation
if(theValue < min) {
      valid = false;
      $(this).addClass('error');
      $(this).closest('label').addClass('red');
      $(this).closest('label').html('Required min value:' + min);
   } else {
      $(this).removeClass('error');
      $(this).closest('label').removeClass('red');
   }
}

编辑:正如@potatopeelings补充的那样,您还需要在change上启动这个