0
votes

I'm new to the react-hook-form world. I'm trying my best to understand but there are things that I'm still missing. I need an Obiwan help!

Here is the problem :

I have an input number which is render using the <Textfield> Material-ui component inside react-hook-form <Controller/ component. On this input I need to have a validation that the number enter sould be between 16 and 99. With Material-UI you can pass the param inputProps={{min:16, max:99}} to block the number on the native input! Great!

But what about if is a user manually enter a value ? Then I want to be able to block it as well in an onBlur validation method, here is what I did:

<TextField
      onBlur={(e) =>{
        const currentValue = Number(e.target.value);
        if (!(currentValue >= minAge && currentValue <= maxAge)) {
            e.target.value = String(minAge);
            ref.current.value = String(minAge);
        }
        onBlur();
        console.log('TextField onBlur(): ', e.target.value);
      }}
      inputRef={ref}

      inputProps={{
        min:minAge,
        max:maxAge
      }}
/>

However when I log the value after a blur it tells me that nothing has change. Please help.

Here is the full file :

import React, {useEffect} from "react";
import { TextField } from "@material-ui/core";
import { Controller, useFormContext } from "react-hook-form";
import { ErrorMessage } from "@hookform/error-message";
import { ErrorMessageContainer } from "./ErrorMessageContainer";
import { FieldWrapper } from "./FieldWrapper";

interface AgeTextboxProps {
  name: string;
  label?: string;
}

export const AgeTextbox = ({ name, label }: AgeTextboxProps) => {
  const { errors, control } = useFormContext();
  const minAge = 16;
  const maxAge = 99

  return (
    <FieldWrapper caption={label}>
      <Controller
        name={name}
        control={control}
        rules={{
          required: { value: true, message: `You must enter the ${label} age` },
          min: { value: minAge, message: `The ${label} age cannot be lower than 16` },
          max: { value: maxAge, message: `The ${label} age cannot be higher than 99` }
        }}
        render={({ onChange, onBlur, value, ref }) => (
          <TextField
            onChange={(e) => onChange(e.target.value)}
            onBlur={(e) =>{
              const currentValue = Number(e.target.value);
              if (!(currentValue >= minAge && currentValue <= maxAge)) {
                  e.target.value = String(minAge);
                  ref.current.value = String(minAge);
              }
              onBlur();
              console.log('TextField onBlur(): ', e.target.value);
            }}
            onFocus={(event) => {
                event.target.select();
            }}
            inputRef={ref}
            value={value || 0}
            error={errors[name] ? true: false}

            role={"textbox"}
            variant="outlined"
            type={"number"}

            inputProps={{
              min:minAge,
              max:maxAge
            }}
          />
        )}
      />

      <ErrorMessage
        errors={errors}
        name={name}
        as={<ErrorMessageContainer />}
      />
    </FieldWrapper>
  );
};

export default AgeTextbox;

Here is a codesandbox link also : https://codesandbox.io/s/eloquent-ishizaka-980qb?file=/src/AgeTextBox.tsx

1

1 Answers

0
votes

Here is what I did for you. May be you wanted this behavior.

I just called onChange inside onBlur

onBlur={(e) => {
              const currentValue = Number(e.target.value);
              if (currentValue < minAge || currentValue > maxAge) {
                onChange(String(minAge));
              } else {
                onChange(e.target.value);
              }
              onBlur();
              console.log("TextField onBlur(): ", e.target.value);
            }}

https://codesandbox.io/s/modest-archimedes-6c1nl?file=/src/AgeTextBox.tsx