jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

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

Open himachalicoderr opened 8 months ago

himachalicoderr commented 8 months ago

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 commented 8 months ago

Looks fine, what doesn't work?