Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. const Validation = {
  2. types: {
  3. require: {
  4. checker(value, option) {
  5. return !!value;
  6. },
  7. message(option) {
  8. return `This field is required.`;
  9. }
  10. },
  11.  
  12. minlength: {
  13. checker(value, option) {
  14. return !!value && value.length >= option;
  15. },
  16. message(option) {
  17. return `This field must has at least ${option} letters.`;
  18. }
  19. },
  20.  
  21. nodigits: {
  22. checker(value, option) {
  23. return !/\d/.test(value);
  24. },
  25. message(option) {
  26. return `This field shouldn't contains digits.`;
  27. }
  28. },
  29.  
  30. isimage: {
  31. checker(value, option) {
  32. console.log(value);
  33. console.log(/\.(jpe?g|png|gif|svg)$/i.test(value));
  34. return /\.(jpe?g|png|gif|svg)$/i.test(value);
  35. },
  36. message(option) {
  37. return `This file isn't an image.`
  38. }
  39. },
  40.  
  41. email: {
  42. checker(value, option) {
  43. return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
  44. },
  45. message(option) {
  46. return `This field doesn't match with appropriate pattern`;
  47. }
  48. }
  49. },
  50.  
  51. errors: {},
  52.  
  53. validate(config, values) {
  54. let checker = null, // username, email, pass, ...
  55. message = null, // function
  56. checkers = null, // require, minlength
  57. option = null; // true, 3
  58.  
  59. // clear existing errors
  60. this.errors = {};
  61.  
  62. if (!config) throw 'You have to pass a configuration!';
  63.  
  64. for (let key in config) {
  65. checkers = ( config[key] ) ? Object.keys( config[key] ) : [];
  66.  
  67. // validation
  68. for (let i = 0; i < checkers.length; i++) {
  69. let item = checkers[i];
  70. checker = this.types[item].checker;
  71. message = this.types[item].message;
  72. option = config[key][item];
  73.  
  74. // throw an error if the validation method is missed
  75. if (!checker) {
  76. throw (`You don't have a validation method for ${checker} option`);
  77. }
  78.  
  79. if ( !checker(values[key], option) ) {
  80. // add an error into the errors object and
  81. this.errors[key] = message(option);
  82.  
  83. // switch to validation of next value
  84. break;
  85. }
  86. }
  87.  
  88. }
  89.  
  90. return this.errors;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement