login-form-validator.ts 1.1 KB

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