-
Notifications
You must be signed in to change notification settings - Fork 937
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create dynamic validation schema. #559
Comments
This is the only open source one available right now - https://www.npmjs.com/package/json-schema-to-yup I'm working on something similar because it didn't suit my needs, but it's not ready for open source yet. |
In case someone is trying to create yupschema on the fly. With some help, I was able to do it without using any external package.
|
@vijayranghar this approach is solid! thanks for sharing |
Thanks @vijayranghar for sharing it. was looking for that exact way to solve it. |
@vijayranghar Great example, just one thing I can't get my head around is this ... |
@vijayranghar one more question, how to add to an existing validation schema? Let's say I already have two inputs inside the form that doesn't get generated dynamically and they already have validation inside an existing schema, how to add to that the dynamic validation? |
@vijayranghar is there any way to support object and array in implementation? |
@vijayranghar this is elegant. Thank you for sharing. |
@vijayranghar thank you!! |
Edit. Just a little
|
Although this issue is resolved.. for those looking for a way to do this via a utility I just released this: https://www.npmjs.com/package/json-schema-yup-transformer |
Can you explain how your project is different / better / more appealing than the existing one? https://www.npmjs.com/package/json-schema-to-yup Competition is good, but why not just work with the existing one to improve it? |
I’ve contributed to schema to yup, it’s a good project...however decided to build my own because:
The main difference I see with schema to yup is that is intended to work with all sorts of schemas but does not strictly adhere to their rules. Hope that helps. |
@ritchieanesco Fantastic reasons! You should add... written in typescript. =) I just took a look and you've got nice test coverage. I'll definitely go with yours when I need it. Keep up the great work. |
@lookfirst how can we add conditional validation here, like |
For this to work your
Then you can pass it to the function:
|
Hi everyone! import * as Yup from 'yup'
const schemaGenerator = data => Yup.object().shape({
name: Yup.string().required('this field is required'),
email: Yup.string().email('enter a valid email').required('this field is required'),
address: Yup.object().shape({
city: Yup.string().required('this field is required'),
neighborhood: (() => {
let validation = Yup.string()
if (data?.address?.street) {
validation = validation.required('this field is required')
}
return validation
})(), // lambda function here to create neighborhood schema dinamically!
street: Yup.string()
})
}) So, to: schemaGenerator({
name: '',
email: '',
address: {
city: '',
neighborhood: '',
street: ''
}
}) I have corresponding Yup schema: Yup.object().shape({
name: Yup.string().required('this field is required'),
email: Yup.string().email('enter a valid email').required('this field is required'),
address: Yup.object().shape({
city: Yup.string().required('this field is required'),
neighborhood: Yup.string(),
street: Yup.string()
})
}) And to: schemaGenerator({
name: '',
email: '',
address: {
city: '',
neighborhood: '',
street: 'something'
}
}) I have corresponding Yup schema: Yup.object().shape({
name: Yup.string().required('this field is required'),
email: Yup.string().email('enter a valid email').required('this field is required'),
address: Yup.object().shape({
city: Yup.string().required('this field is required'),
neighborhood: Yup.string().required('this field is required'),
street: Yup.string()
})
}) |
@vijayranghar thas is nice!!! thank you very much, do you know how to add a nullable validation to a date field with this approach? |
Hi, I have the following schema requirement:
getAlpha2Code is function which returns the Alpha2Code of a particular country from its dial code. |
@Waqqars987 I was wondering the same. I have a JSON that contains the inputs and although Im able to get min and max working. Required never seems to pickup
Input:
|
Required does work for me. However, I can't figure out how to make other Yup functions work as per my requirements. |
What shape is your JSON? I've attached mine above |
{ |
What should the object for |
how to validate the two fields value are same or not when creating dynamic for static i can use - but how to create this object dynamic? |
Just wanted to share an expanded version of all of the great ideas in here. This works with nested objects, as well as arrays. I'm sure there is a shorter way to do this, but I haven't gotten around to refactoring yet. It does have a bunch of tests but I'll update as I find issues. This thread really saved my butt! It takes an array of fields like so: const fields = [
{
name: 'applicant.0.firstName', // in an array
label: 'First name',
validationType: 'string',
validations: [
{
type: 'required',
params: ['Required']
}
]
},
{
name: 'person.lastName', // nested in an object
label: 'Last name',
validationType: 'string',
validations: [
{
type: 'required',
params: ['Required']
}
]
},
{
name: 'email', // non nested, non array
label: 'Email',
validationType: 'string',
validations: [
{
type: 'required',
params: ['Required']
}
]
}
] and returns this: yup.object().shape({
applicant: yup.array().of(yup.object.shape({
firstName: yup.string().required()
})),
person: yup.object().shape({
lastName: yup.string().required()
}),
email: yup.string().required()
}) Here is the source: import * as yup from 'yup'
const getValidationSchema = (fields) => {
const schema = fields.reduce((schema, field) => {
const { name, validationType, validationTypeError, validations = [] } = field
const isObject = name.indexOf('.') >= 0
if (!yup[validationType]) {
return schema
}
let validator = yup[validationType]().typeError(validationTypeError || '')
validations.forEach(validation => {
const { params, type } = validation
if (!validator[type]) {
return
}
validator = validator[type](...params)
})
if (!isObject) {
return schema.concat(yup.object().shape({ [name]: validator }))
}
const reversePath = name.split('.').reverse()
const currNestedObject = reversePath.slice(1).reduce((yupObj, path, index, source) => {
if (!isNaN(path)) {
return { array: yup.array().of(yup.object().shape(yupObj)) }
}
if (yupObj.array) {
return { [path]: yupObj.array }
}
return { [path]: yup.object().shape(yupObj) }
}, { [reversePath[0]]: validator })
const newSchema = yup.object().shape(currNestedObject)
return schema.concat(newSchema)
}, yup.object().shape({}))
return schema
}
export default getValidationSchema |
This is not working and it returns a cyclic dependency error |
Hey, Is there any suggestion for converting Joi description into the Yup ? |
How to validate array length? example data:
|
I have a JSON from which I'm trying to create dynamic form and validation. I'm using
Yup
along withFormik
. I want to create the validation schema after iterating over the form elements validation key but I'm not sure how to do this.I want to create something like after iterating over the
validation
but I'm unable to do so.Which I will send to
Formik
. I looked into many links, even posted on SO but couldn't find any useful lead.Codesandbox
The text was updated successfully, but these errors were encountered: