如何使用 Chakra UI 仅接受数字作为输入值

问题描述 投票:0回答:2

我有一个输入要求用户输入他们的电话号码。但是,用户当前可以输入字母并仍然提交表单。似乎输入上的 type="tel" 属性没有执行任何操作。我该如何解决这个问题?

<FormControl
  isRequired
  isInvalid={touched.number && !values.number}
  mb={2}
  width='100%'
>
  <FormLabel fontSize='lg' fontFamily='Proxima Nova' fontWeight='500'>
    Phone number
  </FormLabel>

  <Input
    type='tel'
    name='number'
    h={10}
    borderColor='#24392E'
    errorBorderColor='#ef5350'
    placeholder='Phone number'
    value={values.number}
    onChange={handleChange}
    onBlur={onBlur}
    _hover={{
      borderColor: '#7fa87f',
    }}
  />
  <FormErrorMessage>Required</FormErrorMessage>
</FormControl>
chakra-ui
2个回答
0
投票

不是最优雅的解决方案,但您可以尝试以下方法:

// Can add this to some global constant file for all regex patterns
const numericalRegexPattern = new RegExp('^[0-9]+$');
const handleNonNumericalKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
  if (!numericalRegexPattern.test(event.key)) {
    event.preventDefault();
  }
}

// Other code

<FormControl
  isRequired
  isInvalid={touched.number && !values.number}
  mb={2}
  width='100%'
>
  <FormLabel fontSize='lg' fontFamily='Proxima Nova' fontWeight='500'>
    Phone number
  </FormLabel>

  <Input
    type='tel'
    name='number'
    h={10}
    borderColor='#24392E'
    errorBorderColor='#ef5350'
    placeholder='Phone number'
    value={values.number}
    onChange={handleChange}
    onBlur={onBlur}
    _hover={{
      borderColor: '#7fa87f',
    }}
    onKeyPress={handleNonNumericalKeyPress} // ADD THIS
  />
  <FormErrorMessage>Required</FormErrorMessage>
</FormControl>

0
投票

我只是使用了这个解决方案,我只能输入数字,当输入字母时它什么也不做

<FormControl isInvalid={errors.randomWordsCount}>
        <FormLabel htmlFor="randomWordsCount">Random Words Amount</FormLabel>
        <Input
          id="randomWordsCount"
          {...register('randomWordsCount', {
            required: 'This field is required',
            pattern: {
              value: /^[1-9][0-9]*$/,
              message: 'Please enter only numbers greater than 0.',
            },
          })}
          borderColor={'brand.100'}
          type="number"
        />
    <FormControl
© www.soinside.com 2019 - 2024. All rights reserved.