vue监听el-input输入禁止emoji表情

测试提出el-input输入emoji表情,提交时会报错,因为后台未做判断,现要求前端这边做处理。

自定义指令:代码如下

import emojiRegex from 'emoji-regex';  //npm install emoji-regex
Vue.directive('clearEmoij', {
  bind(el, binding, vnode, oldVnode) {
    const regex = emojiRegex();
    const obj = el.querySelectorAll('.el-input__inner,.el-textarea__inner')[0];
    let zclearNoNum = function (e) {
      if(e.target.composing) return;
      let match = regex.exec(obj.value); //也可以直接用正则表达式判断
      if(match) {
        /*for (let i=0;i<match.length;i++) {
          obj.value = obj.value.replace(match[i],"");
        }*/
        obj.value = obj.value.replace(/(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g, "");
        zclearNoNum(e);
      }
      // 触发v-model的更新
      obj.dispatchEvent(new Event('input'));
    }
    let zblur = function (e) {
      zclearNoNum(e);
      setTimeout(()=>{
        let match = regex.exec(obj.value);
        if(match) {
          obj.value = obj.value.replace(/(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g, "");
          zclearNoNum(e);
        }
        // 触发v-model的更新
        obj.dispatchEvent(new Event('change'));
      }, 50)
    }
    obj.onkeyup = zclearNoNum;
    obj.onblur = zblur;

    function onCompositionStart (e) {
      e.target.composing = true
    }
    function onCompositionEnd (e) {
      e.target.composing = false
      obj.dispatchEvent(new Event('input'));
    }
    // https://segmentfault.com/a/1190000009246058
    obj.addEventListener('compositionstart', onCompositionStart)
    obj.addEventListener('compositionend', onCompositionEnd)
  },
  update(el, binding, vnode, oldVnode) {}
})

//vue html代码 在el-input中添加自定义指令v-clear-emoji
<el-form-item label="工号" prop="username" >
<el-input v-model="addForm.username" v-clear-emoij auto-complete="off" maxlength='18' placeholder="请输入工号" clearable @keyup.enter.native="searchData" ref="zusername"></el-input>
</el-form-item>
 

输入emoji表情或者复制emoji表情时,会自动刷新清除emoji表情。

上一篇:一日一技:使用二分法排查正则表达式的异常


下一篇:正则表达式