全局数字验证
This commit is contained in:
81
src/components/AmountInputBox/AmountInputBox.js
Normal file
81
src/components/AmountInputBox/AmountInputBox.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @desc 验证整数类型数字方法
|
||||
* @param {Object} e
|
||||
* @param {regular} reg 正则
|
||||
* @param {Number} charcode 键盘code
|
||||
* */
|
||||
const checkNumber = (e, reg, charcode) => {
|
||||
if (!reg.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
|
||||
if (e.preventDefault) {
|
||||
e.preventDefault()
|
||||
} else {
|
||||
e.returnValue = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @desc 验证浮点类型小数方法(建议用text类型的表单)
|
||||
* @param {Object} e
|
||||
* @param {regular} reg 正则
|
||||
* @param {Number} charcode 键盘code
|
||||
* @param {Object} el dom对象
|
||||
* */
|
||||
const checkFloat = (e, reg, charcode, el) => {
|
||||
if (charcode === 46) {
|
||||
if (el.children[0].value.includes('.')) {
|
||||
e.preventDefault()
|
||||
}
|
||||
return
|
||||
} else if (
|
||||
!reg.test(String.fromCharCode(charcode)) &&
|
||||
charcode > 9 &&
|
||||
!e.ctrlKey
|
||||
) {
|
||||
if (e.preventDefault) {
|
||||
e.preventDefault()
|
||||
} else {
|
||||
e.returnValue = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author LeeYunxiang
|
||||
* @description 限制数字输入格式 int => 正整数 , num => 自然数(正整数包括0) , float => 正数包括小数(建议用text类型的input表单)
|
||||
* */
|
||||
export default {
|
||||
key: 'positive',
|
||||
func: {
|
||||
inserted(el, bind) {
|
||||
el.addEventListener('keypress', e => {
|
||||
e = e || window.event
|
||||
const charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode
|
||||
let reg = null
|
||||
switch (bind.value) {
|
||||
case 'num':
|
||||
reg = /\d/
|
||||
checkNumber(e, reg, charcode)
|
||||
break
|
||||
case 'int':
|
||||
if (el.children[0].value.length === 0) {
|
||||
reg = /^[1-9]$/
|
||||
} else {
|
||||
reg = /\d/
|
||||
}
|
||||
checkNumber(e, reg, charcode)
|
||||
break
|
||||
case 'float':
|
||||
reg = /\d/
|
||||
checkFloat(e, reg, charcode, el)
|
||||
break
|
||||
case 'notZero':
|
||||
// reg = (/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])$/)
|
||||
reg = (/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/)
|
||||
checkFloat(e, reg, charcode, el)
|
||||
break
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
11
src/components/AmountInputBox/index.js
Normal file
11
src/components/AmountInputBox/index.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import AmountInputBox from './AmountInputBox.js'
|
||||
const directives = [AmountInputBox]
|
||||
export default {
|
||||
install: Vue => {
|
||||
if (directives.length && directives.length > 0) {
|
||||
directives.map(item => {
|
||||
Vue.directive(item.key, item.func)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user