限制只能输入正整数、负整数和0

Ao_min / 2024-10-11 / 原文

value
       .replace(/[^\d^\.^-]+/g, '')   // 把不是数字,不是小数点的过滤掉

      .replace(/[^\d^\-^-]+/g, '')   // 把不是数字,不是负号-的过滤掉

      .replace(/^0+(\d)/, '$1')      // 以0开头,0后面为数字,则过滤掉,取后面的数字

      .replace(/^-0+(\d)/, '-$1')    // 以-0开头,0后面为数字,则过滤掉,取后面的数字

      .replace(/-/g, (match: any, offset: number) => offset === 0 ? '-' : '') // 只允许第一个是负号-

      .replace(/\./, '#').replace(/\./, '').replace(/#/, '\.') // 只保留第一个小数点        

参考链接:https://juejin.cn/post/7374343669207908361?searchId=20241011151026AFCF1166D360D117996D

 

限制只能输入正整数、负整数和0

<el-input
            clearable
            v-model.trim="form.errorCode"
            :placeholder="$t('info.pherrorCode')"
            :disabled="errorCode != undefined"
            @input="handleNumInput(form.errorCode)"
          />
handleNumInput(errorCode) {
      console.log(errorCode);
      errorCode = errorCode
        .replace(/[^\d^\-^-]+/g, '') // 把不是数字,不是小数点的过滤掉
        .replace(/^0+(\d)/, '$1') // 以0开头,0后面为数字,则过滤掉,取后面的数字
        .replace(/^-0+(\d)/, '-$1') // 以-0开头,0后面为数字,则过滤掉,取后面的数字
        .replace(/-/g, (match, offset) => (offset === 0 ? '-' : '')); // 只允许第一个是负号-
      this.$set(this.form, 'errorCode', errorCode);
    },