const yup = require("yup")
//Simple validation
const schemaValidatorObject = yup.object().shape({
price: yup.number(),
year: yup.number().required(),
model: yup.string().required(),
engine: yup.string().required()
});
const car = {
year: 200,
model: "Hyundai",
engine: "Petrol",
price: 2000
};
schemaValidatorObject.validate(car).then(function(value) {
console.log(value)
}).catch(function(err){
console.log(err)
})
// Dependent Validation
let dependentValidation = yup.object().shape({
isMorning: yup
.boolean(),
tea: yup.boolean().when("isMorning", {
is: true,
then: yup.boolean().required()
})
});
dependentValidation.validate({ isMorning: true}, {abortEarly: false}).then(function(value) {
console.log(value)
}).catch(function(err){
console.log(err)
})
// Dependent on multiple fields
const multipleDependentValidation = yup.object().shape({
isMorning: yup
.boolean(),
isSunday: yup.boolean(),
coffee: yup.number().when(['isMorning', 'isSunday'], {
is: (isMorning, isSunday) => {
return true
},
then: yup.number().required()
}),
});
multipleDependentValidation.validate({ isMorning: true, isSunday: true, coffee: true }).then(function(value) {
console.log(value)
}).catch(function(err){
console.log(err)
})
// Custom Validation
let customValidation = yup.object().shape({
bevrage: yup.string().test('is-tea',
'${path} is not tea',
value => value === 'tea')
});
customValidation.validate({ bevrage: "tea"}).then(function(value) {
console.log(value)
}).catch(function(err){
console.log(err)
})
// Async custom validation
let orderTea = yup.object().shape({
bevrage: yup.string().test('is-tea',
'${path} is not tea',
async (value) => await value === "tea")
});
await orderTea.validate({ bevrage: "coffee"})