How to only accept numbers as values to an input using Chakra UI

36 views Asked by At

I have an input that requires the user to input their phone number. However, the user can currently input letters and still submit the form. It seems that the type="tel" attribute on the input doesn't do anything. How do I solve this?

<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>
3

There are 3 answers

0
JP Roussel On

Not the most elegant solution BUT you can try the following:

// 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
Arman Ghazaryan On

I use React hook form, simply this code below handles your case very well... I can only type numbers, when I enter a letter it just does nothing

<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
0
Ida Soboleva On

You can add some validation in your handleChange function to remove all characters that are not numbers

    const handleChange = useCallback((inputValue: string) => {
        const newValue = inputValue.replace(/\D/g, "");
        // rest
    }, []);