Reputation: 401
I have come across a scenario where I want the 'email' property to be required if 'type' value is 'online'. In a generic point a view I have a field that may be required or not depending on another fields value. How would I go about solving this scenario?
"properties": {
"type": {
"type": "string",
"required": true
},
"email": {
"type": "string"
"required": //true or false depending on what 'type' is
}
}
Upvotes: 1
Views: 177
Reputation: 6576
Declare all potentially not required field as non-required, and use an operation hook before save
to validate the fields in function of your custom logic.
Inside your model.js file, implement the hook with the logic you need. For instance if type is 'A' and requires an email but there is none provided in the request, generate an error and call next(err)
. This way, the request will be denied.
MyModel.observe('before create', function(ctx, next) {
if(ctx.instance){
data = ctx.instance
} else {
data = ctx.data
{
if(data.type =='A' && !data.email){
next(new Error('No email provided !')
} else {
next();
}
});
Upvotes: 1
Reputation: 401
Cleaned up@overdriver's code to make it more implementable
MyModel.observe('before save', (ctx, next) => {
let obj = ctx.instance;
if(obj.type == 'A' && obj.email == null){
next(new Error('No email provided !'));
}
else {
next();
}
});
Upvotes: 0