Last active
October 26, 2017 11:09
-
-
Save slaveofcode/b0726a1053e5f960623489dd768a6af0 to your computer and use it in GitHub Desktop.
Joi Condition Schema
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
const Joi = require('joi') | |
const main = () => { | |
const VALID_TITLES = ["Mr.", "Mrs.", "Ms."] | |
const ADDRESS_HOME = "Home" | |
const ADDRESS_OFFICE = "Office" | |
const VALID_ADDRESS_TYPES = [ADDRESS_HOME, ADDRESS_OFFICE] | |
const digitalSchema = Joi.object().keys({ | |
payment_type: Joi.string().trim().required(), | |
title: Joi.string().valid(VALID_TITLES).required(), | |
first_name: Joi.string().trim().required(), | |
email: Joi.string().email().required(), | |
phone: Joi.string().required() | |
}) | |
const nonDigitalSchema = digitalSchema.keys({ | |
addressType: Joi.string().valid(VALID_ADDRESS_TYPES).required(), | |
city: Joi.string().trim().required() | |
}).when(Joi.object({ addressType: Joi.equal(ADDRESS_HOME)}).unknown(), { | |
then: digitalSchema.keys({ | |
addressHome: Joi.string().trim().required(), | |
rt: Joi.string().trim().required(), | |
rw: Joi.string().trim().required(), | |
postalCodeHome: Joi.string().trim().required() | |
}), | |
otherwise: digitalSchema.keys({ | |
company: Joi.string().trim().required(), | |
building: Joi.string().trim().required(), | |
divisionOrFloor: Joi.string().trim().required(), | |
addressOffice: Joi.string().trim().required(), | |
postalCodeOffice: Joi.string().trim().required(), | |
}) | |
}) | |
const testDigital = { | |
payment_type: 'bank_transfer', | |
title: 'Mr.', | |
first_name: 'Aditya', | |
email: '[email protected]', | |
phone: '085716114422' | |
} | |
const testHome = { | |
payment_type: 'bank_transfer', | |
title: 'Mr.', | |
first_name: 'Aditya', | |
email: '[email protected]', | |
phone: '085716114422', | |
addressType: 'Home', | |
city: 'Bekasi', | |
addressHome: 'Jl. S. Parman', | |
rt: '01', | |
rw: '02', | |
postalCodeHome: '17171' | |
} | |
const testOffice = { | |
payment_type: 'bank_transfer', | |
title: 'Mr.', | |
first_name: 'Aditya', | |
email: '[email protected]', | |
phone: '085716114422', | |
addressType: 'Office', | |
city: 'Bekasi', | |
company: 'TADA', | |
building: 'Kuningan', | |
divisionOrFloor: '5L', | |
addressOffice: 'Sudirman', | |
postalCodeOffice: '18367' | |
} | |
console.log('Test result: ', Joi.validate(testDigital, digitalSchema)) | |
console.log('Test result: ', Joi.validate(testHome, nonDigitalSchema)) | |
console.log('Test result: ', Joi.validate(testOffice, nonDigitalSchema)) | |
} | |
// run by execute node joi_conditional_schema on console | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment