Skip to content
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

I want to create dynamic schema object of yup using json array #2185

Open
himachalicoderr opened this issue Mar 17, 2024 · 1 comment
Open

Comments

@himachalicoderr
Copy link

Hi there,

this is my code for generating yup object

import { object, string, number } from 'yup';

const validationRules = {
name: {
type: 'string',
required: true,
},
age: {
type: 'number',
positive: true,
integer: true,
required: true,
},
};

function generateYupSchema(rules) {
const yupSchema = {};

for (const fieldName in rules) {
const fieldRules = rules[fieldName];

let schema = null;

switch (fieldRules.type) {
  case 'string':
    schema = string();
    break;
  case 'number':
    schema = number();
    break;
  default:
    throw new Error(`Unsupported type for field ${fieldName}`);
}

if (fieldRules.required) {
  schema = schema.required('This field is required');
}

if (fieldRules.positive) {
  schema = schema.positive('This field must be a positive number');
}

if (fieldRules.integer) {
  schema = schema.integer('This field must be an integer');
}

yupSchema[fieldName] = schema;

}

return object().shape(yupSchema);
}

const yupSchema = generateYupSchema(validationRules);

i tried every possibility but no luck.

tried yup.string() or yup.number()

but every time results is different

i want like

{
name: yup.string(). required(),
number : yup.number().integer(). required()
}

how can i do this

@jquense
Copy link
Owner

jquense commented Mar 24, 2024

Looks fine, what doesn't work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants