Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Last active January 26, 2022 20:19
Show Gist options
  • Save iRoachie/c42e80774dd359b2aaeb6d18a9b73487 to your computer and use it in GitHub Desktop.
Save iRoachie/c42e80774dd359b2aaeb6d18a9b73487 to your computer and use it in GitHub Desktop.
Yup validation of comma delimited string
const schema = yup.object({
id: yup
.array()
.transform((value, originalValue, context) => {
if (context.isType(value) && value !== null) {
return value;
}
return originalValue ? String(originalValue).split(/[\s,]+/) : [];
})
.of(yup.string())
.min(1)
.required(),
});
// Tests
schema.validate({}); // fails
schema.validate({ id: '' }); // fails
schema.validate({ id: '123' }); // passes
schema.validate({ id: '123,321' }); // passes
// Returns
schema.validate({ id: '123,321' }); // ['123','321']
@iRoachie
Copy link
Author

Source/inspiration - jquense/yup#564 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment