Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Check the docs (V7): https://react-hook-form.com/api/useform/register

<input
  type="number"
  {...register("test", {
    valueAsNumber: true,
  })}
/>

If not using type="number"

<input
  {...register("test", {
    valueAsNumber: true,
    pattern:{
       value: /^(0|[1-9]\d*)(\.\d+)?$/
    },
  })}
/>

You can still use validate.

<input
  {...register("test", {
    valueAsNumber: true,
    validate: (value) => value > 0,
  })}
/>
about 4 years ago · Juan Pablo Isaza Denunciar

0

use something liket this

const allowOnlyNumber=(value)=>{
   return value.replace(/[^0-9]/g, '')
}

return (
    <Controller
      control={control}
      name={name}
      render={({ field: { onChange, value }, fieldState: { error } }) => (
        <TextField
          {...restProps}
          onChangeText={(text)=>onChange(allowOnlyNumber(text))}
          value={value}
          defaultValue={defaultValue}
          error={(error && error.message) as TxKeyPath}
        />
      )}
      defaultValue={defaultValue}
    />
  )
about 4 years ago · Juan Pablo Isaza Denunciar

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda