login-form-validator.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { body, validationResult } from 'express-validator';
  2. // form rules
  3. export const inviteRules = () => {
  4. return [
  5. body('invitedForm.username')
  6. .matches(/^[\da-zA-Z\-_.]+$/)
  7. .withMessage('Username has invalid characters')
  8. .not()
  9. .isEmpty()
  10. .withMessage('Username field is required'),
  11. body('invitedForm.name').not().isEmpty().withMessage('Name field is required'),
  12. body('invitedForm.password')
  13. .matches(/^[\x20-\x7F]*$/)
  14. .withMessage('Password has invalid character')
  15. .isLength({ min: 6 })
  16. .withMessage('Password minimum character should be more than 6 characters')
  17. .not()
  18. .isEmpty()
  19. .withMessage('Password field is required'),
  20. ];
  21. };
  22. // validation action
  23. export const inviteValidation = (req, res, next) => {
  24. const form = req.body;
  25. const errors = validationResult(req);
  26. if (errors.isEmpty()) {
  27. Object.assign(form, { isValid: true });
  28. req.form = form;
  29. return next();
  30. }
  31. const extractedErrors: string[] = [];
  32. errors.array().map(err => extractedErrors.push(err.msg));
  33. req.flash('errorMessages', extractedErrors);
  34. Object.assign(form, { isValid: false });
  35. req.form = form;
  36. return next();
  37. };
  38. // form rules
  39. export const loginRules = () => {
  40. return [
  41. body('loginForm.username')
  42. .matches(/^[\da-zA-Z\-_.@]+$/)
  43. .withMessage('Username has invalid characters')
  44. .not()
  45. .isEmpty()
  46. .withMessage('Username field is required'),
  47. body('loginForm.password')
  48. .matches(/^[\x20-\x7F]*$/)
  49. .withMessage('Password has invalid character')
  50. .isLength({ min: 6 })
  51. .withMessage('Password minimum character should be more than 6 characters')
  52. .not()
  53. .isEmpty()
  54. .withMessage('Password field is required'),
  55. ];
  56. };
  57. // validation action
  58. export const loginValidation = (req, res, next) => {
  59. const form = req.body;
  60. const errors = validationResult(req);
  61. if (errors.isEmpty()) {
  62. Object.assign(form, { isValid: true });
  63. req.form = form;
  64. return next();
  65. }
  66. const extractedErrors: string[] = [];
  67. errors.array().map(err => extractedErrors.push(err.msg));
  68. req.flash('errorMessages', extractedErrors);
  69. Object.assign(form, { isValid: false });
  70. req.form = form;
  71. return next();
  72. };