How to make generic function for validation which return error mesages?

不问归期 提交于 2021-02-11 15:24:59

问题


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

helperText={
          (errors.firstName &&
            errors.firstName.type === "required" &&
            "First name is required") ||
          (errors.firstName &&
            errors.firstName.type === "pattern" &&
            "Invalid user")
        }

instead of above line i want to create a function which return error message (depending on type) example it is type of required it shows me it is required .if it pattern error show invalid user.


回答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.

const App = () => {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = 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"] };

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

  function makeHelpText(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 (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      <TextField
        inputRef={register(makeRegister(validateItems.method))}
        label="First name"
        variant="outlined"
        name={validateItems.name}
        required
        helperText={makeHelpText(
          errors[validateItems.name],
          validateItems.method
        )}
        error={errors.firstName ? true : false}
      />

      <Button color="primary" type="submit" variant="contained" fullWidth>
        Submit
      </Button>
    </form>
  );
};



来源:https://stackoverflow.com/questions/60070467/how-to-make-generic-function-for-validation-which-return-error-mesages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!