首页 > 解决方案 > Selectize.js 创建:验证 CREATE 输入

问题描述

这是我的 selectize.js 函数

$("#addmobilenumbers").selectize({
    inputClass: 'form-control selectize-input', 
    dropdownParent: "body",persist: false,
    create: true //need to create and allow only digits
});

我只想numeric(只输入手机号码)createmin/max length. 我该怎么做?

标签: jqueryvalidationselectize.js

解决方案


使用createFilteronInitialize选项

createFilter:在使用给定的正则表达式创建之前验证选项

/^[0-9]{10}$/ - accepts only numbers between 0-9 of length 10 digits

onInitialize : 用于设置 maxlength / 限制输入为数字的事件

this.$control_input.prop('maxlength', 10) 

this.$control_input.on('input', function() {
  this.value = this.value.replace(/[^\d]/g, '')
})

$("#addmobilenumbers").selectize({
  inputClass: 'form-control selectize-input',
  dropdownParent: "body",
  persist: false,
  create: true,
  createFilter: /^[0-9]{10}$/,
  onInitialize: function() {
    this.$control_input.prop('maxlength', 10)

    this.$control_input.on('input', function() {
      this.value = this.value.replace(/[^\d]/g, '')
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js" integrity="sha512-pF+DNRwavWMukUv/LyzDyDMn8U2uvqYQdJN0Zvilr6DDo/56xPDZdDoyPDYZRSL4aOKO/FGKXTpzDyQJ8je8Qw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.default.min.css" integrity="sha512-H955AcCOE/fUjX4XWkN0FwjCYVV/zioSF6VpUKCcrGdR1Wa8paFWYixWYp85npbnx3i1kZCH4Rm4TRxut2+d5A==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<select id="addmobilenumbers" multiple></select>

参考

https://selectize.dev/docs.html#configuration


推荐阅读