validator.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const Merchant = require("../models/merchant.js");
  2. module.exports = {
  3. merchant: async function(merchant){
  4. if(!this.isSanitary([merchant.name])){
  5. return "Name contains illegal characters";
  6. }
  7. if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(merchant.email)){
  8. return "Invalid email address";
  9. }
  10. let checkMerchant = await Merchant.findOne({email: merchant.email});
  11. if(checkMerchant){
  12. return "An account with that email address already exists";
  13. }
  14. let checkPassword = this.password(merchant.password, merchant.confirmPassword);
  15. if(this.password(checkPassword !== true)){
  16. return checkPassword;
  17. }
  18. return true;
  19. },
  20. password: function(password, confirmPassword){
  21. if(password.length < 10){
  22. return "Password must contain at least 10 characters";
  23. }
  24. if(password !== confirmPassword){
  25. return "Passwords do not match";
  26. }
  27. return true;
  28. },
  29. quantity: function(num){
  30. if(isNaN(num) || num === ""){
  31. return "Quantity must be a number";
  32. }
  33. if(num < 0){
  34. return "Quantity cannot be a negative number";
  35. }
  36. return true;
  37. },
  38. ingredient: function(ingredient){
  39. if(!this.isSanitary([ingredient.name, ingredient.category, ingredient.unit])){
  40. return "Ingredient contains illegal characters";
  41. }
  42. return true;
  43. },
  44. recipe: function(recipe){
  45. if(!this.isSanitary([recipe.name])){
  46. return "Ingredient contains illegal characters";
  47. }
  48. if(isNaN(recipe.price) || recipe.price === ""){
  49. return "Price must be a number";
  50. }
  51. if(recipe.price < 0){
  52. return "Price cannot be a negative number";
  53. }
  54. for(let i = 0; i < recipe.ingredients.length; i++){
  55. let checkQuantity = this.quantity(recipe.ingredients[i].quantity);
  56. if(checkQuantity !== true){
  57. return checkQuantity;
  58. }
  59. }
  60. return true;
  61. },
  62. isSanitary: function(strings){
  63. let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
  64. for(let i = 0; i < strings.length; i++){
  65. for(let j = 0; j < disallowed.length; j++){
  66. if(strings[i].includes(disallowed[j])){
  67. return false;
  68. }
  69. }
  70. }
  71. return true;
  72. }
  73. }