How to use the class-validator.validate function in class-validator

To help you get started, we’ve selected a few class-validator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github javieraviles / node-typescript-koa-rest / src / controller / user.ts View on Github external
public static async createUser(ctx: BaseContext) {

        // get a user repository to perform operations with user
        const userRepository: Repository = getManager().getRepository(User);

        // build up entity user to be saved
        const userToBeSaved: User = new User();
        userToBeSaved.name = ctx.request.body.name;
        userToBeSaved.email = ctx.request.body.email;

        // validate user entity
        const errors: ValidationError[] = await validate(userToBeSaved); // errors is an array of validation errors

        if (errors.length > 0) {
            // return BAD REQUEST status code and errors array
            ctx.status = 400;
            ctx.body = errors;
        } else if (await userRepository.findOne({ email: userToBeSaved.email })) {
            // return BAD REQUEST status code and email already exists error
            ctx.status = 400;
            ctx.body = 'The specified e-mail address already exists';
        } else {
            // save the user contained in the POST body
            const user = await userRepository.save(userToBeSaved);
            // return CREATED status code and updated user
            ctx.status = 201;
            ctx.body = user;
        }
github magishift / magishift.core / packages / crud / src / pipes / dtoValidation.pipe.ts View on Github external
private async plainToClass(dto: TDto, obj: any): Promise {
    if (!obj) {
      return undefined;
    }

    const result = plainToClassFromExist(dto, obj);

    const errors = await validate(result, {
      whitelist: true,
    });

    if (errors.length > 0) {
      throw new BadRequestException(errors);
    }

    const repository = getRepository(this.entity);

    await Promise.all(
      repository.metadata.columns.map(async (column: ColumnMetadata) => {
        const propType = GetPropertyType(repository.metadata.columns, column.propertyName);

        if (
          result[column.propertyName] &&
          propType === 'uuid' &&
github chukwuemekachm / GraphQL-API / src / validators / index.ts View on Github external
const validateRequest = async (
  Validator: any,
  payload: IPayload,
  action?: string,
): Promise => {
  let resource = new Validator(payload);
  let validationErrors = {};

  Object.entries(payload).forEach(([key, value]) => {
    resource[key] =
      typeof value === 'string' ? value.replace(/  +/g, '').trim() : value;
  });

  const errors = await validate(resource, {
    validationError: { target: false },
    skipMissingProperties: action === 'update' ? true : false,
  });

  if (errors.length === 0) {
    return false;
  }

  for (let error of errors) {
    validationErrors = {
      ...validationErrors,
      [error.property]: Object.entries(error.constraints).map(
        ([, value]) => value,
      ),
    };
  }
github kevquincke / node-api-base / src / controllers / api / v1 / user / user.controller.ts View on Github external
router.post('/', async (req: Request, res: Response) => {
  let user: User = await User.findOne({ email: req.body.email });

  if (user) {
    return res.status(400).send('Email already in use');
  }

  user = new User(req.body);

  const errors = await validate(user);

  if (!_.isEmpty(errors)) {
    return res.status(400).send(getValidationErrors(errors));
  }

  user = await user.save();

  res.header('x-auth-token', user.token).send(_.pick(user, ['id', 'email']));
});
github chanlito / nestjs-extensions / src / dto / dto.pipe.ts View on Github external
async transform(value: any, { metatype }: ArgumentMetadata) {
    const dtoOptions = this.reflector.get(DTO_META_KEY, metatype);
    if (value && dtoOptions) {
      const entity = plainToClass(metatype as any, value);
      const errors = await validate(entity, dtoOptions);
      if (errors.length > 0) {
        throw new UnprocessableEntityException({
          message: 'Validation Failed.',
          errors: errors.map(e => this.mapErrors(e, ''))
        });
      }
      return entity;
    }
    return value;
  }
github ubiq / shokku / src / server / jsonrpc / jsonrpc.validation.pipe.ts View on Github external
async transform(value, metadata: ArgumentMetadata) {
    const { metatype } = metadata
    if (!metatype || !this.isValidMetatype(metatype)) {
      this.throwInvalidParamsException()
    }

    const object = plainToClass(metatype, value)
    const errors = await validate(object, validatorOpts)
    if (errors.length > 0) {
      this.throwInvalidParamsException()
    }

    return value
  }
github hackoregon / openelections / api / models / entity / Campaign.ts View on Github external
async validateAsync() {
        const errors = await validate(this);
        this.errors = errors;
        await this.validateGovernmentAsync();
    }
github nestjs / nest / sample / 01-cats-app / src / common / pipes / validation.pipe.ts View on Github external
async transform(value: any, metadata: ArgumentMetadata) {
    const { metatype } = metadata;
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }
github santaz1995 / nestjs-cqrs-starter / src / pipe / validation.pipe.ts View on Github external
public async transform(value, metadata: ArgumentMetadata) {

        const { metatype } = metadata;

        if (!metatype || !this.toValidate(metatype)) {
            return value;
        }

        const entity = plainToClass(metatype, value);

        const errors = await validate(entity, { validationError: { target: false } });

        if (errors.length > 0) {
            throw new BadRequestException(errors);
        }

        return entity;
    }