vue3进阶(二)-封装utils方法——禁止输入框特殊字符校验 & form表单特定字符校验 & 自定义指令app.directive之防抖指令v-throttle

vue3进阶(二)-封装utils方法——禁止输入框特殊字符校验 & form表单特定字符校验 & 自定义指令app.directive之防抖指令v-throttle

4、引用的校验方法

src\utils\validate.ts

//  禁止输入框特殊字符校验 
export function replaceCommonText(e: any) {
  if (!checkSpecificKeyWord(e)) {
    // 提交关键字
    ElMessage({
      message: '不能包含关键词: ' + wordKey,
      type: 'warning',
    })
    const y = e.replace(wordKey, '')
    return y
  } else {
    const str = e.replace(
      /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~!@#¥%……&*()——\-+={}|《》?:“”  ]/g,
      ''
    )
    const y = str.replace(/\s+/g, '')
    return y
  }
}

/**
 * @description form表单特定字符校验
 * @param value
 * @returns {boolean}
 */
export function validateCommonText(rule: any, value: any, callback: any) {
  const noChars = "[`~!#$^&*\"()=|{}': ; ',\\[\\].<>/?~!#¥……&*()——|{}【】‘;:”“'。,、?]‘'@ /%"
  const v = value || ''

  for (let i = 0; i < noChars.length; i++) {
    const char = noChars[i]
    if (v.indexOf(char) != -1) {
      callback(new Error('不能使用特殊字符'))
      return
    }
  }
使用教程

特殊字符校验

  1. 介绍:输入框禁止输入特殊字符

第一步引入:

import { replaceCommonText } from '@src/utils/validate'

第二步页面应用:

<el-input v-model.trim="formInline.prjName" @input="(e) => (formInline.prjName = replaceCommonText(e))"/>
  1. 介绍:form 表单特殊字符验证

第一步引入:

import { validateCommonText } from '@src/utils/validate'

第二步在 rules 校验中用法:

 { validator: validateCommonText, trigger: 'blur' },

公共方法

全局防抖 - 添加防抖指令

<el-button v-throttle="3000" > 保存 </el-button>   
防抖方法

library\plugins\directive.ts

import type { DirectiveBinding } from 'vue'

export function setup(app: any) {
  /**
   * @description 自定义指令v-throttle
   */
  app.directive('throttle', {
    mounted(el: any, binding: DirectiveBinding) {
      let { throttleTime } = binding.value
      if (!throttleTime) {
        throttleTime = 1000
      }
      let timer: any
      let disable = false
      el.addEventListener(
        'click',
        (event: any) => {
          if (timer) {
            clearTimeout(timer)
          }
          if (!disable) {
            disable = true
          } else {
            event && event.stopImmediatePropagation()
          }
          timer = setTimeout(() => {
            timer = null
            disable = false
          }, throttleTime)
        },
        true
      )
    },
  })
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值