I have custom methods for validators
export function required(value: any) {
const { path, createError } = this;
if (value === null || value === undefined || !value) {
return createError({ path: path, message: 'common.required-error.key' });
}
return true;
}
export function email(value: string) {
const regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const testResult = regex.test(String(value).toLowerCase());
const { path, createError } = this;
if (!testResult) {
return createError({ path: path, message: 'common.email-error.key' });
}
return true;
}
These are the methods I use to validate input fields Custom form components and controls
<Form validators={{ control1: required, control2: [required, email] }} submitHandler={submit}>
<FormControl type="text" formControlName="control1"></FormControl>
<FormControl type="email" formControlName="control2"></FormControl>
</Form>
inside the Form.tsx component using the library I create my test function methods
const { register, handleSubmit, formState, getValues } = useForm({
resolver: yupResolver(buidlValidators(validators, t)),
// mode: 'onChange',
// reValidateMode: 'onChange',
});
function buidlValidators(validators: Record<string, yup.TestFunction | yup.TestFunction[]>, t: (key: string) => any) {
const result = {};
for (const key in validators) {
const value = validators[key];
if (Array.isArray(value)) {
result[key] = functionСhain(value, key);
} else {
result[key] = yup.mixed().test(value.name, null, value);
}
}
console.log({ buidlValidators: result })
return yup.object().shape(result);
}
function functionСhain(functions: yup.TestFunction[], name: string) {
let validator = yup.mixed();
for (const value of functions) {
validator = validator.test(value.name, null, value);
}
return validator;
}
But I am getting this error
control1: {message: "common.required-error.key", type: "required", ref: input}
control2: {message: "common.required-error.key", type: "required", ref: input}
but I would like to get something like this
control1: {message: "common.required-error.key", type: "required", ref: input}
control2: {message: ["common.required-error.key", "common.email-error.key"], type: "required", ref: input}
I would like to understand how to do it correctly in order to get the result that I want