Skip to content

Instantly share code, notes, and snippets.

@nyk0r
Created November 15, 2018 06:06
Show Gist options
  • Save nyk0r/2a20b424ae2f9a12b86778aa20be7b75 to your computer and use it in GitHub Desktop.
Save nyk0r/2a20b424ae2f9a12b86778aa20be7b75 to your computer and use it in GitHub Desktop.
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
var schema = {
properties: {
country: { type: 'string', enum: ['RU', 'US', 'UZ'] },
postalCode: { type: 'string', maxLength: 10 }
},
if: {
properties: {
country: { enum: ['US'] }
}
},
then: {
properties: {
postalCode: { type: 'string', pattern: '^\\d{5}(-\\d{4})?$' },
}
},
required:[ 'country', 'postalCode' ]
};
var validate = ajv.compile(schema);
test({country: 'UZ', postalCode: '00000'});
test({country: 'US', postalCode: 'ZZZZZ'});
test({country: 'US', postalCode: '00000'});
function test(data) {
var valid = validate(data);
if (valid) console.log('Valid!');
else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment