Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!