Last active
July 23, 2018 05:09
-
-
Save herbowicz/5fd75839b47204d730228447c2b5a06e to your computer and use it in GitHub Desktop.
Joi validation example
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
const schema = Joi.number().min(18).max(130); | |
const age = 20; | |
Joi.assert(age, schema); |
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
const userSchema = { | |
id: Joi.number().required(), | |
name: Joi.string().required(), | |
address1: Joi.string(), | |
address2: Joi.string().optional().allow(''), | |
email: Joi.string().email().required(), | |
language: Joi.string().valid(['pl', 'en']).required(), | |
login: Joi.string().required(), | |
password: Joi.string().min(5).required(), | |
repeatPassword: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'Must match password.' } } }), | |
// phone is required, a string of the format XXX-XXX-XXXX | |
phone: Joi.string().regex(/^\d{3}-\d{3}-\d{4}$/).required(), | |
// birthday must be a valid ISO-8601 date | |
// dates before Jan 1, 2004 are not allowed | |
birthday: Joi.date().max('1-1-2004').iso(), | |
// accepts a valid UUID v4 string | |
uuid: Joi.string().guid({version: 'uuidv4'}), | |
// cardNumber must be a valid number | |
cardNumber: Joi.string().creditCard(), | |
}; | |
const clearlyNotUser = { | |
id: 123, | |
name: 'Jan Kowalski', | |
address1: 'ul. Długa 2', | |
address2: '', | |
email: 'jan@kowalski.pl', | |
language: 'pl', | |
login: 'hello', | |
password: 'secret', | |
repeatPassword: 'secret', | |
phone: '123-456-7890', | |
birthday: '10-12-2015' | |
}; | |
Joi.validate(userSchema, schema, {abortEarly: false}, (err, val) => { | |
if (err) { | |
console.log(err); | |
} else { | |
console.log('Data ok.'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment