Created
November 15, 2018 06:06
-
-
Save nyk0r/2a20b424ae2f9a12b86778aa20be7b75 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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