Last active
January 26, 2022 20:19
-
-
Save iRoachie/c42e80774dd359b2aaeb6d18a9b73487 to your computer and use it in GitHub Desktop.
Yup validation of comma delimited string
This file contains 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
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'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source/inspiration - jquense/yup#564 (comment)