Skip to content Skip to sidebar Skip to footer

How To Make Generic Function For Validation Which Return Error Mesages?

Could you please tell me How to make generic function for validation which return error messages? Here is my code https://codesandbox.io/s/react-hook-form-get-started-j39p0 helper

Solution 1:

By the method below, you can

1.put the validation process to common service files 2.make the input fields in your repo managed by single source constant, 3.reuse the error message as you want.

constApp = () => {
  const { register, handleSubmit, errors } = useForm();
  constonSubmit = data => {};

  const validation = [
    { name: "required", value: true, message: "Input required" },
    { name: "pattern", value: /^[A-Za-z]+$/i, message: "Invalid input" }
  ];

  const validateItems = { name: "firstName", method: ["required", "pattern"] };

  functionmakeRegister(checkList) {
    let result = {};
    validation.forEach(item => {
      if (checkList.includes(item.name)) {
        result[item.name] = item.value;
      }
    });
    return result;
  }

  functionmakeHelpText(unit, checkList) {
    console.log(unit);
    let result = "";
    checkList.forEach(name => {
      if (unit && unit.type === name) {
        return (result = validation.find(x => x.name === name).message);
      }
    });
    return result;
  }
  return (
    <formonSubmit={handleSubmit(onSubmit)}noValidate><TextFieldinputRef={register(makeRegister(validateItems.method))}label="First name"variant="outlined"name={validateItems.name}requiredhelperText={makeHelpText(errors[validateItems.name],
          validateItems.method
        )}
        error={errors.firstName ? true:false}
      /><Buttoncolor="primary"type="submit"variant="contained"fullWidth>
        Submit
      </Button></form>
  );
};

Edit React Hook Form - Get Started

Post a Comment for "How To Make Generic Function For Validation Which Return Error Mesages?"