Class which checks the value?

Help!!! you need to create a class to test values on certain criteria. The validation criteria passed to the constructor as an array of objects where each object represents a single criterion
{
name: 'required' /* a string with the unique name of the criterion */,
check: value => { /* logic checks the test to return true, not false */ },
message: value => { /* returns a string with the error message */ }
}
the class should have two methods:
- toggleValidator(name, state) - enables/disables a specific criterion. name - the name of the criterion, state (optional) - boolean the state of the criterion. If state is not supplied, the first call to the method needs to turn off the criterion and the following to include, etc.
- validate(value) - validates the value according to the included criteria. Returns an object:

{
valid: /* true - verification passed false */,
errors: /* Map errors where the key is the name of the criterion, the value - error message */
}
March 19th 20 at 09:14
1 answer
March 19th 20 at 09:16
Solution
Validator function(criterias) {
 let items = criterias.map((item) => ({enabled: true, ...item}));


 this.toggleValidate = function(name, state) {
 let item = items.find((item) => item.name === name);
 if (item) {
 item.enabled = typeof state === 'undefined' ? !item.enabled : state;
}
}


 this.validate = function(value) {
 let valid = true;
 let errors = new Map();

 items.forEach((item) => {
 if (item.enabled && !item.check(value)) {
 valid = false; 
 errors.set(item.name of the item.message(value));
 } 
 }); 

 return {valid, errors};
}
}
thank you, work) but as you can see immediately without syntax classes - sigmund76 commented on March 19th 20 at 09:19
@sigmund76,
class Validator {
 constructor(criterias) {
 this.items = criterias.map((item) => ({enabled: true, ...item}));
}


 toggleValidate(name, state) {
 let item = this.items.find((item) => item.name === name);
 if (item) {
 item.enabled = typeof state === 'undefined' ? !item.enabled : state;
}
}


 validate(value) {
 let valid = true;
 let errors = new Map();

 this.items.forEach((item) => {
 if (item.enabled && !item.check(value)) {
 valid = false; 
 errors.set(item.name of the item.message(value));
 } 
 }); 

 return {valid, errors};
}
}
- favian commented on March 19th 20 at 09:22

Find more questions by tags JavaScript