-
Notifications
You must be signed in to change notification settings - Fork 0
/
boolean.js
47 lines (40 loc) · 1.13 KB
/
boolean.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
const Field = require('./field');
/**
* A true/false field. Handles booleans and strings representing booleans. Serializes to boolean.
*
* @example
* const field = new BooleanField();
*
* field.deserialize(false); // returns false
* field.deserialize('yes'); // returns true
* field.deserialize('123'); // throws validation error
*/
class BooleanField extends Field {
/**
* @param {object} [params]
* @param {boolean} [params.optional]
* @param {boolean} [params.default]
*/
constructor(params) {
super(params);
}
/**
* @returns {boolean}
*/
deserialize(value) {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'string') {
if (value.match(/^(y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON)$/)) {
return true;
}
if (value.match(/^(n|N|no|No|NO|false|False|FALSE|off|Off|OFF)$/)) {
return false;
}
}
throw new Field.ValidationError('Value must be a boolean');
}
}
module.exports = BooleanField;