register-form-validator.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { body, validationResult } from 'express-validator';
  2. // form rules
  3. export const registerRules = () => {
  4. return [
  5. body('registerForm.username')
  6. .matches(/^[\da-zA-Z\-_.]+$/)
  7. .withMessage('Username has invalid characters')
  8. .not()
  9. .isEmpty()
  10. .withMessage('Username field is required'),
  11. body('registerForm.name').not().isEmpty().withMessage('Name field is required'),
  12. body('registerForm.email')
  13. .isEmail()
  14. .withMessage('Email format is invalid.')
  15. .exists()
  16. .withMessage('Email field is required.'),
  17. body('registerForm.password')
  18. .matches(/^[\x20-\x7F]*$/)
  19. .withMessage('Password has invalid character')
  20. .isLength({ min: 6 })
  21. .withMessage('Password minimum character should be more than 6 characters')
  22. .not()
  23. .isEmpty()
  24. .withMessage('Password field is required'),
  25. body('registerForm[app:globalLang]'),
  26. ];
  27. };
  28. // validation action
  29. export const registerValidation = (req, res, next) => {
  30. const form = req.body;
  31. const errors = validationResult(req);
  32. if (errors.isEmpty()) {
  33. Object.assign(form, { isValid: true });
  34. req.form = form;
  35. return next();
  36. }
  37. const extractedErrors: string[] = [];
  38. errors.array().map(err => extractedErrors.push(err.msg));
  39. Object.assign(form, {
  40. isValid: false,
  41. errors: extractedErrors,
  42. });
  43. req.form = form;
  44. return next();
  45. };