禁用将浮动字符粘贴到“输入数字”字段的可能性

时间:2019-03-27 11:40:29

标签: javascript reactjs validation input ecmascript-6

我在尝试禁用<input type='number' />的粘贴浮动数字时遇到问题。我禁用了+ - e E . onKeyDown,但是如何在onPaste上禁用它呢?目前,我只能对e.preventDefault()使用onPatste来完全禁用。如何仅禁用+ - e E .

  <CutomInputField
     required
     type='number'
     inputProps={{
       min: '1',
       max: '100',
       autoComplete: 'off',
     }}
     onKeyDown={e =>preventFloatingPointNumber(e)}
     onPaste={e => {
       e.preventDefault()
       // preventFloatingPointNumber(e) //does not work such way
              }
            }
    />

// 'left arrow', 'up arrow', 'right arrow', 'down arrow',
const arrowsKeyCodes = [37, 38, 39, 40];
// 'numpad 0', 'numpad 1',  'numpad 2', 'numpad 3', 'numpad 4', 'numpad 5', 
'numpad 6', 'numpad 7', 'numpad 8', 'numpad 9'
const numPadNumberKeyCodes = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105];

const preventFloatingPointNumber = e => {
// allow only [0-9] number, numpad number, arrow,  BackSpace, Tab
if ((e.keyCode < 48 && !arrowsKeyCodes.includes(e.keyCode) || e.keyCode > 57 &&
    !numPadNumberKeyCodes.includes(e.keyCode)) &&
    !(e.keyCode === 8 || e.keyCode === 9))
    e.preventDefault()

0 个答案:

没有答案