【问题标题】:Jquery maximum 3 validation for textfield文本字段的 Jquery 最多 3 次验证
【发布时间】:2018-11-26 04:38:15
【问题描述】:

我正在尝试验证我的表单的文本字段不允许超过 3 个整数值。

<div class="form-group col-lg-5">
  {!! Form::label('qty', 'TradedQuantity:') !!} 
  {!! Form::text('qty', null, ['class'=>'form-control'])!!}
</div>
$(document).ready(function() {
  $('#form').validate({ // initialize the plugin
    qty: {
      required: true,
      maxlength: 3
    }
  });
});

我不知道我在这里缺少什么。

我已经完成了,但是直到没有工作:maxlength: 3

【问题讨论】:

  • 为什么不直接使用maxlength="3"
  • 大声笑,这是问题内容中的错误......我已经编辑了它。 @RoryMcCrossan
  • 不,我的意思是使用 HTML maxlength 属性。那么在JS中就不需要验证长度了。
  • 哦!您是对的,但是,我在这里提出问题是因为,当我使用 HMTL maxlength : 3 时,它会在提交表单后发送消息。我想在填写表格时向用户发出警告。 @RoryMcCrossan
  • 如果您确实想为此使用 jQuery 验证,那么正确的规则名称是 maxlength,而不是 maxjqueryvalidation.org/maxlength-method

标签: javascript jquery laravel validation


【解决方案1】:

问题是因为 jQuery validate() 没有 max 规则。如果要限制可以输入的字符数,正确的规则名称是maxlength。另请注意,验证规则需要放在rules 对象中。我强烈建议您阅读插件的documentation

$('#form').validate({
  rules: {
    qty: {
      required: true,
      maxlength: 3
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="form">
  <div class="form-group col-lg-5">
    <label>
      Traded Quantity
      <input type="text" name="qty" class="form-control" />
    </label>
    <button type="submit">Submit</button>
  </div>
</form>

请注意,您可以直接在input 上使用maxlength HTML 属性。

【讨论】:

  • 我还发布了我的textfield的屏幕。
  • 我为你更新了答案。您缺少 rules 属性。
  • jquery 验证只通过 id?不是班级的名称,ID和标签,这是可能的吗?? -@Rory McCrossan
  • 不,它只使用name 属性,因为所有input 元素都应该有一个name
  • 当我更改标签类和 id 时,这不会影响验证工作??? -@Rory McCrossan
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 2011-11-09
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多