Created
June 30, 2020 17:50
-
-
Save jeffhandley/dee69c7318aa603b4d194a6bc45a980f to your computer and use it in GitHub Desktop.
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
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See jeffhandley/strickland#36