F
F
frogqwetr2022-03-17 14:23:57
React
frogqwetr, 2022-03-17 14:23:57

Why does the form validation change when submitting the form?

I have a registration form that has two fields from material ui, validation happens using the react hook form library. The problem is that before the "Sign up" button is clicked, the validation works fine in the onBlur mod, but when I click the button, the form stops working normally, it seems to change the onBlur mod to onChange, because of this, instead of one validation request user (an asynchronous method found in the validatorsFormRegistrationFieldLogin object in the react hook form library's validate method), this request is sent for each character entered in the field.

Below is a picture of the requests before clicking the button and after (requests are sent when a new character is added)

623318015bfbe057863612.png
6233180c5d35d686779456.png

Registration form component

import { Button, TextField } from "@mui/material";
import { useForm, Controller } from "react-hook-form";
import {
  validatorsFormRegistrationFieldLogin,
  validatorsFormRegistrationFieldPassword,
} from ...
interface FormRegistrationField {
  name: string;
  password: string;
}

const RegistrationForm: FC = () => {
  const dispatch = useDispatch();
  const { control, handleSubmit, reset, formState } =
    useForm<FormRegistrationField>({
      mode: "onBlur",
    });

  const testSubmit = (data: FormRegistrationField) => {
    console.log(data);
    reset();
  };

  return (
    <div className="registration-form">
      <form onSubmit={handleSubmit(testSubmit)}>
        <Controller
          name="name"
          rules={validatorsFormRegistrationFieldLogin}
          render={({ field, fieldState: { error } }) => (
            <TextField
              error={!!error?.message}
              helperText={error?.message}
              label="login"
              {...field}
              value={field.value || ""}
            />
          )}
          control={control}
        />
        <Controller
          name="password"
          shouldUnregister={true}
          rules={validatorsFormRegistrationFieldPassword}
          render={({ field, fieldState: { error } }) => (
            <TextField
              type="password"
              error={!!error?.message}
              helperText={error?.message}
              label="password"
              {...field}
              value={field.value || ""}
            />
          )}
          control={control}
        />
        <Button
          disabled={!formState.isValid || formState.isSubmitting}
          type="submit"
        >
          Зарегистрироваться
        </Button>
      </form>
    </div>
  );
};


Form Validators
const defaultRequriedMessage = "Поле должно быть заполнено"

const checkIfSuchUserExists = async (nameUser: string): Promise<boolean> => {
    console.log("request users")
    const receviedUser = await getUserInformation(nameUser)
    return !!receviedUser
}

export const validatorsFormRegistrationFieldLogin:  Omit<RegisterOptions, 'valueAsNumber' | 'valueAsDate' | 'setValueAs' | 'disabled'> = {
    required: defaultRequriedMessage,
    validate: async (value: string) => {
        const isUserWithThisNameFound = await checkIfSuchUserExists(value)
        if (isUserWithThisNameFound){
            return "Пользователь с таким именем уже существует"
        }
        return true
    }
}

export const validatorsFormRegistrationFieldPassword: Omit<RegisterOptions, 'valueAsNumber' | 'valueAsDate' | 'setValueAs' | 'disabled'> = {
    required: defaultRequriedMessage,
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
frogqwetr, 2022-03-18
@frogqwetr

For those who may be facing a similar issue. I found a solution: specify in the options that you pass to the hook one more property - "reValidateMode".

const { control, handleSubmit, reset, formState } =
    useForm<FormRegistrationField>({
      mode: "onBlur", 
      reValidateMode: "onBlur", // вот это свойство нужно добавить
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question