Using yup how can i make it so if value of boughtby === "none" then it should throw a error. Since now it only works if value is "" but I wanna make is so if the value is "none" than it also throws a error.
const NewUserSchema = Yup.object().shape({
createDate: Yup.string().nullable().required('Create date is required'),
boughtby: Yup.string().required("Cannot be none")
});
const defaultValues = useMemo(
() => ({
createDate: details?.dealDetails[0]?.created_date || null,
// I would like this to have "none" as default value, it accepts
// the value if it is "none" but it throws error if it is "".
// How do I implement so it throws error on both?
boughtby: details?.dealDetails[0]?.bought_by || "",
// eslint-disable-next-line react-hooks/exhaustive-deps
[details]
);
const methods = useForm({
resolver: yupResolver(NewUserSchema),
defaultValues,
});
CodePudding user response:
One way you can do this is via regex, by accepting any value that is not "none"
:
const NewUserSchema = Yup.object().shape({
createDate: Yup.string().nullable().required('Create date is required'),
boughtby: Yup.string().matches(/^(?!none).*$/, "Cannot be none").required("Cannot be none")
});