validation-strategy.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * @filedescription Validation Strategy
  3. */
  4. "use strict";
  5. //-----------------------------------------------------------------------------
  6. // Class
  7. //-----------------------------------------------------------------------------
  8. /**
  9. * Container class for several different validation strategies.
  10. */
  11. class ValidationStrategy {
  12. /**
  13. * Validates that a value is an array.
  14. * @param {*} value The value to validate.
  15. * @returns {void}
  16. * @throws {TypeError} If the value is invalid.
  17. */
  18. static array(value) {
  19. if (!Array.isArray(value)) {
  20. throw new TypeError("Expected an array.");
  21. }
  22. }
  23. /**
  24. * Validates that a value is a boolean.
  25. * @param {*} value The value to validate.
  26. * @returns {void}
  27. * @throws {TypeError} If the value is invalid.
  28. */
  29. static boolean(value) {
  30. if (typeof value !== "boolean") {
  31. throw new TypeError("Expected a Boolean.");
  32. }
  33. }
  34. /**
  35. * Validates that a value is a number.
  36. * @param {*} value The value to validate.
  37. * @returns {void}
  38. * @throws {TypeError} If the value is invalid.
  39. */
  40. static number(value) {
  41. if (typeof value !== "number") {
  42. throw new TypeError("Expected a number.");
  43. }
  44. }
  45. /**
  46. * Validates that a value is a object.
  47. * @param {*} value The value to validate.
  48. * @returns {void}
  49. * @throws {TypeError} If the value is invalid.
  50. */
  51. static object(value) {
  52. if (!value || typeof value !== "object") {
  53. throw new TypeError("Expected an object.");
  54. }
  55. }
  56. /**
  57. * Validates that a value is a object or null.
  58. * @param {*} value The value to validate.
  59. * @returns {void}
  60. * @throws {TypeError} If the value is invalid.
  61. */
  62. static "object?"(value) {
  63. if (typeof value !== "object") {
  64. throw new TypeError("Expected an object or null.");
  65. }
  66. }
  67. /**
  68. * Validates that a value is a string.
  69. * @param {*} value The value to validate.
  70. * @returns {void}
  71. * @throws {TypeError} If the value is invalid.
  72. */
  73. static string(value) {
  74. if (typeof value !== "string") {
  75. throw new TypeError("Expected a string.");
  76. }
  77. }
  78. /**
  79. * Validates that a value is a non-empty string.
  80. * @param {*} value The value to validate.
  81. * @returns {void}
  82. * @throws {TypeError} If the value is invalid.
  83. */
  84. static "string!"(value) {
  85. if (typeof value !== "string" || value.length === 0) {
  86. throw new TypeError("Expected a non-empty string.");
  87. }
  88. }
  89. }
  90. exports.ValidationStrategy = ValidationStrategy;