login-form-validator.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { ErrorV3 } from '@growi/core/dist/models';
  2. import { body, validationResult, type ValidationChain } from 'express-validator';
  3. // form rules
  4. export const loginRules = (minPasswordLength: number): ValidationChain[] => {
  5. return [
  6. body('loginForm.username')
  7. .matches(/^[\da-zA-Z\-_.+@]+$/)
  8. .withMessage('message.Username or E-mail has invalid characters')
  9. .not()
  10. .isEmpty()
  11. .withMessage('message.Username field is required'),
  12. body('loginForm.password')
  13. .matches(/^[\x20-\x7F]*$/)
  14. .withMessage('message.Password has invalid character')
  15. .isLength({ min: minPasswordLength })
  16. .withMessage(new ErrorV3('message.Password minimum character should be more than n characters', undefined, undefined, { number: minPasswordLength }))
  17. .not()
  18. .isEmpty()
  19. .withMessage('message.Password field is required'),
  20. ];
  21. };
  22. // validation action
  23. export const loginValidation = (req, res, next): ValidationChain[] => {
  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. Object.assign(form, {
  34. isValid: false,
  35. errors: extractedErrors,
  36. });
  37. req.form = form;
  38. return next();
  39. };