天天看点

InputRegZen.vue 正则Input 限制输入框输入内容

核心内容 已经 perfect,没有用外库,原生完成 用的 iview的Input组件 封装

// InputRegZen.vue
<template>
  <div>
    <Input v-model="currentValue"
           ref="inputRef"
           :maxlength="maxlength"
           :placeholder="placeholder"
           :disabled="disabled"
           @input="inputHandle" />
  </div>
</template>

<script>
export default {
  name: 'InputRegZen',
  props: {
    regStr: {
      type: String,
      default: "中文数字字母_"
    },
    maxlength: {
      type: Number,
      default: 30,
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: ''
    },
  },
  components: {},
  data () {
    return {
      currentValue: this.value.toString(),
    }
  },
  watch: {
    value: function (val) {
      this.currentValue = this.value.toString()
    },
  },
  computed: {},
  methods: {
    inputHandle (val) {
      if (this.clearSpot(val) !== val) { // 有非法字符
        const diff = this.getDiff(val, this.clearSpot(val))
        this.$nextTick(() => {
          this.currentValue = this.value
          this.$nextTick(() => {
            this.$refs.inputRef.$refs.input.setSelectionRange(diff, diff)
          })
        })
      } else { // 全部合法
        this.$emit('input', val)
        this.$emit('validateField') // 这句很重要
        // 外层需要 每次 验证一下
        // @validateField="$refs.yourRef.validateField('yourFiledName')"
      }
    },
    getDiff (str1, str2) {
      let ret = 0
      for (let i = 0; i < str1.length; i++) {
        if (str1.substr(i, 1) === str2.substr(i, 1)) {
          // next
        } else {
          ret = i
          break
        }
      }
      return ret
    },
    clearSpot (vStr) {
      // return vStr.replace(/[^0-9]/ig, '')
      const restList = {
        "数字": /[^0-9]/ig,
        "中文数字字母_": /[^a-zA-Z0-9_\u4e00-\u9fa5]+$/ig,
      }
      return vStr.replace(restList[this.regStr], '')
    }
  },
  created () { },
  activated () { },
  mounted () { },
  beforeDestroy () { }
}
</script>

<style>
</style>