UNPKG

1.44 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Validator');
7
8module.exports = class BooleanValidator extends Base {
9
10 constructor (config) {
11 super({
12 trueValue: true,
13 falseValue: false,
14 strict: false,
15 castValue: true,
16 ...config
17 });
18 }
19
20 getMessage () {
21 return this.createMessage(this.message, 'Value must be "{true}" or "{false}"', {
22 'true': this.trueValue,
23 'false': this.falseValue
24 });
25 }
26
27 validateAttr (attr, model) {
28 const value = model.get(attr);
29 if (this.strict ? value === this.trueValue : value == this.trueValue) {
30 if (this.castValue) {
31 model.set(attr, this.trueValue);
32 }
33 } else if (this.strict ? value === this.falseValue : value == this.falseValue) {
34 if (this.castValue) {
35 model.set(attr, this.falseValue);
36 }
37 } else {
38 this.addError(model, attr, this.getMessage());
39 }
40 }
41
42 validateValue (value) {
43 if ((!this.strict && (value == this.trueValue || value == this.falseValue))
44 || (this.strict && (value === this.trueValue || value === this.falseValue))) {
45 return;
46 }
47 return this.getMessage();
48 }
49};
\No newline at end of file