Source: api/utility/user.utility.js

  1. /**
  2. * @module userUtility
  3. * @description Provides utility functions for user validation.
  4. */
  5. /**
  6. * Validates the request body for required fields.
  7. * @param {Object} body - The request body.
  8. * @param {string[]} requiredFields - The list of required fields.
  9. * @throws {Error} - Throws an error if any of the required fields are missing.
  10. * @memberof module:userUtility
  11. */
  12. const validateRequestBody = (body, requiredFields) => {
  13. for (const field of requiredFields) {
  14. if (!body?.[field]) {
  15. throw new Error(`Please provide a ${field}`);
  16. }
  17. }
  18. };
  19. /**
  20. * Validates the user's name.
  21. * @param {string} name - The name of the user.
  22. * @throws {Error} - Throws an error if the name is invalid.
  23. * @memberof module:userUtility
  24. */
  25. const validateName = (name) => {
  26. if (!name) {
  27. throw new Error('Name is required');
  28. }
  29. if (name.trim().split(' ').length < 2) {
  30. throw new Error('Invalid name. Please provide your first and last name');
  31. }
  32. };
  33. /**
  34. * Validates the user's email.
  35. * @param {string} email - The email of the user.
  36. * @throws {Error} - Throws an error if the email is invalid.
  37. * @memberof module:userUtility
  38. */
  39. const validateEmail = (email) => {
  40. if (!email) {
  41. throw new Error('Email is required');
  42. }
  43. const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  44. if (!emailRegex.test(email)) {
  45. throw new Error('Invalid email. Please provide a valid email address');
  46. }
  47. };
  48. /**
  49. * Validates the user's password.
  50. * @param {string} password - The password of the user.
  51. * @throws {Error} - Throws an error if the password is invalid.
  52. * @memberof module:userUtility
  53. */
  54. const validatePassword = (password) => {
  55. if (!password) {
  56. throw new Error('Password is required');
  57. }
  58. if (password.length < 5 || !/\d/.test(password)) {
  59. throw new Error(
  60. 'Invalid password. Password must be at least 5 characters long and contain at least one number',
  61. );
  62. }
  63. };
  64. /**
  65. * Validates the user's registration data.
  66. * @param {string} name - The name of the user.
  67. * @param {string} email - The email of the user.
  68. * @param {string} password - The password of the user.
  69. * @throws {Error} - Throws an error if any of the registration data is invalid.
  70. * @memberof module:userUtility
  71. */
  72. const validateUserRegistration = (name, email, password) => {
  73. validateName(name);
  74. validateEmail(email);
  75. validatePassword(password);
  76. };
  77. module.exports = {
  78. validateRequestBody,
  79. validateUserRegistration,
  80. validateName,
  81. validateEmail,
  82. validatePassword,
  83. };