允许整数和空格的Jquery规则验证

时间:2014-10-17 12:40:44

标签: jquery jquery-validate

我接受整数的当前验证器是

$( "#UserForm" ).validate({
  rules: {
    contact: {
      required: true,
      number: true,
      minlength: 6,
    }
  }
});

工作正常

但现在我想改变它以便也接受空格。

我的代码应该是什么?请帮助我在jquery

中初学者

1 个答案:

答案 0 :(得分:8)

您可以使用additional-method.js文件中定义的pattern规则

jQuery(function($) {
  $("#UserForm").validate({
    rules: {
      contact: {
        required: true,
        pattern: /^[\d\s]+$/,
        minlength: 6,
      }
    },
    messages: {
      contact: {
        pattern: 'Please enter digits or space characters only'
      }
    }
  });
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form id="UserForm" method="post" action="">
  <div>
    <input name="contact" />
  </div>
  <input type="submit" class="button" value="Submit" />
</form>