S
S
Speakermen2021-11-11 13:07:44
Express.js
Speakermen, 2021-11-11 13:07:44

Is it possible to move express-validator processing to DTO in express?

How can you render in Dto? It’s bad without TS, but I don’t know how to set it up in express in NestJs, it came out of the box) I’m taking a

course to train and get to know sockets. On Udemy Create a Twitter Clone with Node.js, Socket.IO and MongoDB

router.post(
  '/register',
  body('firstName').not().isEmpty().trim().escape(),
  body('lastName').not().isEmpty().trim().escape(),
  body('username').not().isEmpty().trim().escape(),
  body('email').isEmail(),
  body('password'),
  body('passwordConf').custom((value, { req }) => {
    if (value !== req.body.password) {
      throw new Error('Password confirmation does not match password');
    }

    // Indicates the success of this synchronous custom validator
    return true;
  }),
  (req, res, next) => {
    authService.register();
    console.log(validationResult(req));

    res.render('register', { title: 'Twitter' });
  }
);


To get something like this

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const ReqBody = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.body;
  },
);


@UseGuards(LocalAuthGuard)
  @Post('/register')
  async register(
    @ReqBody(new ValidationPipe({ validateCustomDecorators: true }))
    createRegisterDto: CreateRegisterDto,
  ) {
    return this.authService.register(createRegisterDto);
  }


import { IsEmail, IsNotEmpty, MaxLength, MinLength } from 'class-validator';

export class CreateRegisterDto {
  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  @MinLength(1)
  @MaxLength(255)
  firstName: string;

  @IsNotEmpty()
  @MinLength(1)
  @MaxLength(255)
  lastName: string;

  @IsNotEmpty()
  @MinLength(6)
  @MaxLength(255)
  password: string;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question