Yup

node v6.17.1
version: master
endpointsharetweet
const yup = require('yup'); let schema = yup .object() .shape({ // our "basic" requirements emailAddress: yup.string().required().email(), // email will be validated by yup (required) red: yup.boolean(), orange: yup.boolean(), green: yup.boolean() }) ; // extended validation schema = schema.test( // this test is added additional to any other (build-in) tests 'myCustomCheckboxTest', null, // we'll return error message ourself if needed (obj) => { // only testing the checkboxes here if ( obj.red || obj.orange || obj.green ) { return true; // everything is fine } return new yup.ValidationError( '❗ Check at least one checkbox', null, 'myCustomFieldName' ); } ); const validateOptions = { abortEarly: false }; const validateMsgGood = '✔ Everything seems fine to me'; // for testing purpose null;
// no checkbox checked -> error const testValues1 = { emailAddress: 'someone@somewhere.com', red: false, orange: false, green: false }; await schema.validate(testValues1, validateOptions) .then(() => { return validateMsgGood; }) .catch((err) => err.errors);
// no email address -> error const testValues2 = { red: true, orange: false, green: false }; await schema.validate(testValues2, validateOptions) .then(() => { return validateMsgGood; }) .catch((err) => err.errors);
// checkbox orange checked and email address -> okay const testValues3 = { emailAddress: 'someone@somewhere.com', red: false, orange: true, green: false }; await schema.validate(testValues3, validateOptions) .then(() => { return validateMsgGood; }) .catch((err) => err.errors);
// no email address -> error const testValues4 = { emailAddress: 'wrong@no', red: true, orange: false, green: false }; await schema.validate(testValues4, validateOptions) .then(() => { return validateMsgGood; }) .catch((err) => err.errors);
Loading…

no comments

    sign in to comment