问题
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