register-form-validator.ts 1.7 KB

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