Skema: Skip a Property
Usage of `when`
by kaelzhang
HTML
<script src="https://unpkg.com/skema/umd/jsfiddle.js"></script>
<script src="https://unpkg.com/skema/umd/skema.min.js"></script>
JavaScript
const {shape} = Skema
log('example: always skip')
const A = shape({
foo: {
// always skip processing the value by setting `when:false`
when: false,
validate: v => v > 10
}
// Purify the data, so that the result does not have dirty properties
}, true)
const a = A.from({foo: 1})
success(a.foo === undefined)
// But if you assign the property directly, validation does not skip
throws(() => {
a.foo = 1
})
a.foo = 11
success('a.foo', a.foo)
log('example: depends to skip')
const User = shape({
isMarried: Boolean,
marriageDate: {
type: Date,
when: function () {
return this.parent.isMarried
}
}
}, true)
const user = User.from({
isMarried: false,
marriageDate: 'hahaha'
})
success(user.marriageDate === undefined)
throws(() => User.from({
isMarried: true,
marriageDate: 'hahaha'
}))
const user2 = User.from({
isMarried: 1,
marriageDate: '2017-01-01'
})
const typeOf = v => Object.prototype.toString.call(v)
success(
'user2.marriageDate',
user2.marriageDate,
typeOf(user2.marriageDate))
success('user2.isMarried', user2.isMarried)