UI for Zipcoin Blue

validators.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const chalk_1 = require("chalk");
  4. const string_1 = require("../utils/string");
  5. function validate(input, key, validators, errors) {
  6. const throwErrors = typeof errors === 'undefined';
  7. if (!errors) {
  8. errors = [];
  9. }
  10. for (let validator of validators) {
  11. const r = validator(input, key);
  12. if (r !== true) {
  13. errors.push({ message: r, inputName: key });
  14. }
  15. }
  16. if (throwErrors && errors.length > 0) {
  17. throw errors;
  18. }
  19. }
  20. exports.validate = validate;
  21. exports.validators = {
  22. required(input, key) {
  23. if (!input) {
  24. if (key) {
  25. return `${chalk_1.default.green(key)} must not be empty.`;
  26. }
  27. else {
  28. return 'Must not be empty.';
  29. }
  30. }
  31. return true;
  32. },
  33. email(input, key) {
  34. if (!string_1.isValidEmail(input)) {
  35. if (key) {
  36. return `${chalk_1.default.green(key)} is an invalid email address.`;
  37. }
  38. else {
  39. return 'Invalid email address.';
  40. }
  41. }
  42. return true;
  43. },
  44. numeric(input, key) {
  45. if (isNaN(Number(input))) {
  46. if (key) {
  47. return `${chalk_1.default.green(key)} must be numeric.`;
  48. }
  49. else {
  50. return 'Must be numeric.';
  51. }
  52. }
  53. return true;
  54. },
  55. };
  56. function contains(values, { caseSensitive = true }) {
  57. if (!caseSensitive) {
  58. values = values.map(v => typeof v === 'string' ? v.toLowerCase() : v);
  59. }
  60. return function (input, key) {
  61. if (!caseSensitive && typeof input === 'string') {
  62. input = input.toLowerCase();
  63. }
  64. if (values.indexOf(input) === -1) {
  65. const strValues = values.filter(v => typeof v === 'string'); // TODO: typescript bug?
  66. const mustBe = (strValues.length !== values.length ? 'unset or one of' : 'one of') + ': ' + strValues.map(v => chalk_1.default.green(v)).join(', ');
  67. if (key) {
  68. return `${chalk_1.default.green(key)} must be ${mustBe} (not ${typeof input === 'undefined' ? 'unset' : chalk_1.default.green(input)})`;
  69. }
  70. else {
  71. return `Must be ${mustBe} (not ${typeof input === 'undefined' ? 'unset' : chalk_1.default.green(input)})`;
  72. }
  73. }
  74. return true;
  75. };
  76. }
  77. exports.contains = contains;