Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 10, 2020 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velotiotech/c3a485cee74504762d7a0b4fa27d2f52 to your computer and use it in GitHub Desktop.
Save velotiotech/c3a485cee74504762d7a0b4fa27d2f52 to your computer and use it in GitHub Desktop.
import * as yup from 'yup';
/** Adding just additional methods here */
yup.addMethod(yup.string, "URL", function(...args) {
return this.url(...args);
});
const validator = function (message) {
return this.test('is-string-boolean', message, function (value) {
if (isEmpty(value)) {
return true;
}
if (['Y', 'N'].indexOf(value) !== -1) {
return true;
} else {
return false;
}
});
};
yup.addMethod(yup.string, "stringBoolean", validator);
yup.addMethod(yup.string, "StringBoolean", validator);
export function createYupSchema(schema, config) {
const { field, validationType, validations = [] } = config;
if (!yup[validationType]) {
return schema;
}
let validator = yup[validationType]();
validations.forEach((validation) => {
const { params, type } = validation;
if (!validator[type]) {
return;
}
validator = validator[type](...params);
});
if (field.indexOf('.') !== -1) {
// nested fields are not covered in this example but are eash to handle tough
} else {
schema[field] = validator;
}
return schema;
}
export const getYupSchemaFromMetaData = (
metadata,
additionalValidations,
forceRemove
) => {
const yepSchema = metadata.reduce(createYupSchema, {});
const mergedSchema = {
...yepSchema,
...additionalValidations,
};
forceRemove.forEach((field) => {
delete mergedSchema[field];
});
const validateSchema = yup.object().shape(mergedSchema);
return validateSchema;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment