boolean.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. // Load modules
  3. const Any = require('./any');
  4. // Declare internals
  5. const internals = {};
  6. internals.Boolean = class extends Any {
  7. constructor() {
  8. super();
  9. this._type = 'boolean';
  10. }
  11. _base(value, state, options) {
  12. const result = {
  13. value
  14. };
  15. if (typeof value === 'string' &&
  16. options.convert) {
  17. const lower = value.toLowerCase();
  18. result.value = (lower === 'true' || lower === 'yes' || lower === 'on' || lower === '1' ? true
  19. : (lower === 'false' || lower === 'no' || lower === 'off' || lower === '0' ? false : value));
  20. }
  21. if (typeof value === 'number' &&
  22. options.convert) {
  23. result.value = (value === 1 ? true
  24. : (value === 0 ? false : value));
  25. }
  26. result.errors = (typeof result.value === 'boolean') ? null : this.createError('boolean.base', null, state, options);
  27. return result;
  28. }
  29. };
  30. module.exports = new internals.Boolean();