How do you know which attribute is called a validation rule?

I perform my own checks in certain fields, so that only certain values ​​are accepted (depending on the field), and the rest are rejected. I would like to write a filter function that checks which attribute is called validation, and from there decides which words are allowed to be used by the attribute. Thus, the model will look something like this:

module.exports = { types: { filter: function(attribute) { if (attribute === 'number') { switch(attribute.value) { case 'one': return true; case 'two': return true; default: return false; } } else if (attribute === 'color') { switch(attribute.value) { case 'red': return true; case 'blue': return true; default: return false; } } }, }, attributes: { number: { type: 'string', required: true, filter: true }, color: { type: 'string', required: true, filter: true } } }; 

Of course, in the usual Sails.js behavior, an β€œ attribute ” will not be an attribute, but an attribute value. (And attribute.value was just an example, I want the attribute value to be there).

So, I want attribute be the actual attribute that I called the validation rule. Is this possible with Sails? I mean, I could write a function for each field in the model, but it would be nice to have a function that suits them all (I have a lot of them).

Thanks.

+7
validation models waterline
source share
1 answer

Ok, so I will answer your question, but this may not be exactly what you want. An attribute can have an β€œenumeration” of how we achieved the final goal:

 attributes: { state: { type: 'string', enum: ['pending', 'approved', 'denied'] } } 

But I will assume that this code is just a contrived example. Here I think this will work.

  module.exports = { types: { filter: function(attribute) { if (attribute === 'number') { switch(attribute.value) { case 'one': return true; case 'two': return true; default: this.validationErrors.push(attribute); return false; } } else if (attribute === 'color') { switch(attribute.value) { case 'red': return true; case 'blue': return true; default: this.validationErrors.push(attribute); return false; } } }, }, attributes: { validationErrors:(function(){ var errors = []; return { push:function(attr){ errors.push(attr); }, get:function(){ return errors; } }; })(), number: { type: 'string', required: true, filter: true }, color: { type: 'string', required: true, filter: true } } }; 

Edit: use attribute method instead of attribute

There are potential problems with this answer. I'm not sure how the waterline handles "this" inside these user-defined functions. Is "this" related to the model? Or an instance of the model we are creating? There are a lot of questions to ask, but maybe this can give you some ideas and create a discussion.

+1
source share

All Articles