Created
January 27, 2020 18:27
-
-
Save tudorilisoi/791c3e99fe2b9afed57785fa38282ce8 to your computer and use it in GitHub Desktop.
yup-validate-object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as yup from 'yup'; | |
const getPostSchema = (catIDs) => { | |
const schema = yup.object().shape({ | |
title: yup.string() | |
.label('Titlul') | |
.required().min(10).max(255), | |
content: yup.string() | |
.label('Textul') | |
.required().min(20), | |
cat_id: yup.number() | |
.label('Categoria') | |
.required().oneOf(catIDs, 'Trebuie să selectaţi o categorie din listă'), | |
}) | |
return schema | |
} | |
export default getPostSchema | |
const getValidationErrors = async (schema, values) => { | |
try { | |
await schema.validate(values, { abortEarly: false }) | |
return false | |
} catch (err) { | |
console.log(`Yup ERRORS`); // => 'ValidationError' | |
// console.log(err.name); // => 'ValidationError' | |
//console.log(err); // => [{ key: 'field_too_short', values: { min: 18 } }] | |
const errors = err.inner.reduce((acc, err) => { | |
const { path, message } = err | |
acc[path] = message | |
return acc | |
}, {}) | |
return errors //if Object.keys(errors).length === 0 the data is valid | |
} | |
} | |
export { getValidationErrors } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment