63 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-01-06 16:01:42 +01:00
import * as yup from 'yup';
2020-01-09 22:54:37 +01:00
// TODO - Translation
2020-01-07 16:00:11 +01:00
const translatedErrors = {
required: 'This value is required',
regex: 'This does not match the format',
string: 'This is not a string',
};
const createYupSchema = form => {
const validation = yup.object().shape(
Object.keys(form).reduce((acc, current) => {
const { type, validations } = form[current];
acc[current] = createYupSchemaEntry(type, validations);
return acc;
}, {})
);
return validation;
};
const createYupSchemaEntry = (type, validations) => {
2020-01-06 16:01:42 +01:00
let schema = yup.mixed();
if (['text'].includes(type)) {
2020-01-07 16:00:11 +01:00
schema = yup.string(translatedErrors.string).nullable();
}
if (['headers'].includes(type)) {
schema = yup
.array()
.of(
yup.object().shape({
key: yup.string().required(),
value: yup.string().required(),
})
)
.nullable();
}
if (['events'].includes(type)) {
schema = yup.array();
2020-01-06 16:01:42 +01:00
}
Object.keys(validations).forEach(validation => {
const validationValue = validations[validation];
switch (validation) {
case 'required':
schema = schema.required(translatedErrors.required);
break;
case 'regex':
schema = schema.matches(validationValue, translatedErrors.regex);
break;
default:
}
});
return schema;
};
2020-01-08 18:28:52 +01:00
export { createYupSchema, createYupSchemaEntry };