Skip to content
Advertisement

How to input only number in react-hook-form

I’m using react-hook-form for my input components, but there is one problem. In some text field, for example, text field for validation that take only number, i don’t know how to do that, with normal textInput, we can use regex, like

 const [numberInput, setNumberInput] = useState("")
  function onTextChanged(value) {
    setNumberInput(value.replace(/[^0-9]/, "")) 
  }

and put that function and hook value on onTextChange and value respectively , i tried same method above on react-hook-form, but it won’t work! i still can input other character like “+” or “-“, of course using numeric keyboard

So here is TextField component

export interface HTextFieldProps extends TextFieldProps {
  control: Control<any>
  name: string
  defaultValue?: string
}

/**
 * Describe your component here
 */
export const HTextField = function HookformTextField(props: HTextFieldProps) {
  const { name, control, defaultValue = "", ...restProps } = props

  return (
    <Controller
      control={control}
      name={name}
      render={({ field: { onChange, value }, fieldState: { error } }) => (
        <TextField
          {...restProps}
          onChangeText={onChange}
          value={value}
          defaultValue={defaultValue}
          error={(error && error.message) as TxKeyPath}
        />
      )}
      defaultValue={defaultValue}
    />
  )
}

Here is when i use this

         <HTextField
            onChangeText={(value) => onTextChanged(value)}
            value={numberInput}
            name={"times"}
            control={control}
            autoCapitalize="none"
            keyboardType={Platform.OS === "android" ? "numeric" : "number-pad"}
            returnKeyType="done"
            inputStyle={INPUT_STYLE}
            required
          />

So how can i use only number in react-hook-form look like this, thank you a lots

Advertisement

Answer

Solution for integers only

You can just set <TextField /> prop type to number and then there will be only numbers allowed.

<Controller
  control={control}
  name={name}
  render={({ field: { onChange, value }, fieldState: { error } }) => (
    <TextField
      {...restProps}
      onChange={onChange}
      value={value}
      fullWidth
      label="Times"
      defaultValue={defaultValue}
      type="number"
      error={error && error.message}
    />
  )}
  defaultValue={defaultValue}
/>

Edit React Hook Form - Typescript (forked)

Solution for leading zeros or exponent

As noted in the comments here is a version accepting also leading zeros or exponent notation by using RHF’s validate function.

const validate = (value: string) => {
  const matches = value.match(
    /^(?:0.(?:0[0-9]|[0-9]d?)|[0-9]d*(?:.d{1,2})?)(?:e[+-]?d+)?$/
  );
  return matches?.length > 0 || "Not a Number";
};

return (
  <Controller
    control={control}
    name={name}
    rules={{ validate }}
    render={({ field: { onChange, value }, fieldState: { error } }) => (
      <TextField
        {...restProps}
        onChange={onChange}
        value={value}
        fullWidth
        label="Times"
        error={!!error}
      />
    )}
    defaultValue={defaultValue}
  />
);

Edit React Hook Form - Typescript (forked)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement