分为keyup和blur两个场景,同时校验两种场景用户体验感更佳。
一、keypu事件: val为输入框的值,dlen为number类型,dlen值为maxlength-3 (例如:input的maxlength为10,此时传入的值为7)
export const toKeyupFloat2 = (val, dlen) => { if (val.substring(0, 1) === '.') { val = '' } val = val.replace(/^0*(0\.|[1-9])/, '$1') val = val.replace(/[^\d.]/g, '') val = val.replace(/\.{2,}/g, '.') val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') let pos = val.indexOf('.') if (val === '0' && pos !== 1) { val = '0' } if (pos !== -1 && val.length > (pos + 3)) { val = val.substring(0, pos + 3) } if (val.length >= (dlen + 1) && val.indexOf('.') === -1) { val = val.substring(0, dlen) } return val }
二、Blur事件: val为input的值,blur事件主要用来blur掉鼠标点击输入的非正常值
export const toBlurFloat2 = (val) => { val = Number(val).toFixed(2) if (Number(val) === 0) { val = '' } return val }