How to limit Ant InputNumber maxLength

62 Views Asked by At

I am using antd InputNumber component. I wanted to set the maxLength but it doesn't work . I also tried to do it with max attribute to limit the charachters at 12. But none of them worked.

                 <InputNumber
                     required
                    type="number"
                    addonBefore="+"
                    defaultValue={994}
                    controls={false}
                    value={combinedState?.phoneNumber}
                    onChange={(e)=>  setCombinedState((prevState: any) => ({
                        ...prevState,
                        phoneNumber: e,
                      }));}
                    onKeyDown={(event) => {
                      if (
                        event.key == 'e' ||
                        event.key == '+' ||
                        event.key == '-' ||
                        event.key == '.'
                      ) {
                        event.preventDefault();
                      }
                    }}
                    onInput={(e) => {
                      if (e.length > 4) {
                        console.log('s');
                      }
                    }}
                    min={0}
                    max={999999999999}
                  />
1

There are 1 best solutions below

2
Fabio Nettis On

Here is a possible solution using the onChange event handler of the input to stop the user from entering more than the desired amount of characters:

interface Props extends InputNumberProps {
  maxLength?: number;
}

export default function MyInput(props: Props): JSX.Element {
  const { onChange, maxLength = -1, ...rest } = props;

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.currentTarget.value.toString();
    if (value.length === maxLength) return;
    onChange?.(e);
  }, [onChange, maxLength]);

  return <InputNumber {...rest} onChange={handleChange} />;
}

export type { Props as MyInputProps };

Please note that you should do some research on your own before posting to stack overflow. A look at the antd component documentation here would've probably sufficed.