Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffhandley/dee69c7318aa603b4d194a6bc45a980f to your computer and use it in GitHub Desktop.
Save jeffhandley/dee69c7318aa603b4d194a6bc45a980f to your computer and use it in GitHub Desktop.
var strickland = require("strickland");
var validate = strickland.default;
var required = strickland.required;
var length = strickland.length;
var minLength = strickland.minLength;
var form = strickland.form;
var data = {
name: '',
phones: [
{
areaCode: '555',
number: '555-1234'
},
{
areaCode: '555',
number: '1234'
}
]
}
var phoneValidator = {
areaCode: length(3, 3),
number: length(8, 8)
};
function phonesValidator(phones, context) {
if (phones && !Array.isArray(phones)) {
return false;
}
var isValid = true;
var validationResults = phones.map((phone) => {
var result = validate(phoneValidator, phone, context);
isValid = isValid && result.isValid;
return result;
});
return {
isValid,
validationResults,
...(isValid ? {} : { message: 'At least one phone number is invalid' })
};
}
var validator = {
name: required({message: 'name is required'}),
phones: [
minLength(1, { message: 'You must specify at least one phone number' }),
phonesValidator
]
};
var result = validate(validator, data);
console.log(JSON.stringify(result, null, 2));
@jeffhandley
Copy link
Author

Pardon the lack of ES6 usage -- I whipped this up super quick without any tooling

@jeffhandley
Copy link
Author

jeffhandley commented Jun 30, 2020

I could imagine an arrayOf higher-order validator too.

var validator = {
    name: required({message: 'name is required'}),
    phones: [
        minLength(3, {message: 'You must specify at least one phone number'}),
        arrayOf({
            areaCode: length(3, 3),
            number: length(7, 7)
        })
    ]
};

@jeffhandley
Copy link
Author

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