I saw available solution like Yup: How to validate field only when it exists? it requires adding additional boolean to the existing shape, which I do not want to do.
Is there way I can simply evaluate the field itself?
I created a sandbox: https://codesandbox.io/s/yup-date-validation-test-optional-self-check-906iz?file=/src/index.js
import * as yup from "yup";
const optionalCheck = yup.string().when("nickName", {
is: (value) => value?.length,
then: (rule) =>
rule.matches(
/^[aA-zZ\s]+$/,
`this can only have characters, no digits or symbols.`
)
});
const schema = yup.object().shape({
nickName: optionalCheck,
firstName: yup.string().required("required")
});
schema
.validate({ nickName: "11-11-1111", firstName: "aaa" }, { abortEarly: false })
.catch((err) => {
console.log(JSON.stringify(err, null, 4));
console.log("-----");
console.log(err.message);
})
.then(() => console.log("valid1"));
I will always get Error: Cyclic dependency, node was:"nickName"
Any suggestions?
UPDATE
I found another solution! now it works! Yup validation for a non-required field