class-validator#validate TypeScript Examples

The following examples show how to use class-validator#validate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 8 votes vote down vote up
export function mapClass(cls: ClassConstructor<object>): RequestHandler {
    return async (req: Request, res: Response, next: NextFunction) => {
        // Map to class
        let obj: object = plainToInstance(cls, req.body);

        // Validate class
        let errors = await validate(obj, {
            skipMissingProperties: true,
            whitelist: true,
            forbidNonWhitelisted: false,
            forbidUnknownValues: true,
        });
        if (errors.length > 0) {
            res.status(400).send({ error: true, errors: formatValidationErrors(errors) });
            return;
        }

        // Set validated class to locals
        res.locals.input = obj;
        next();
    };
}
Example #2
Source File: users.controller.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@httpPost('/')
  public async create(
    @requestBody() body: Partial<User>,
    req: Request,
    res: Response,
  ) {
    const repository = await this.databaseService.getRepository(UserRepository);
    const user = new User();
    user.email = body.email;
    user.password = body.password;

    const errors = await validate(user);

    if (errors.length !== 0) {
      return res.status(400).json({errors});
    }

    await repository.save(user);
    return res.sendStatus(201);
  }
Example #3
Source File: assessment.controller.ts    From bulwark with MIT License 6 votes vote down vote up
createAssessment = async (req: UserRequest, res: Response) => {
  if (isNaN(req.body.asset)) {
    return res.status(400).json('Asset ID is invalid');
  }
  const asset = await getConnection()
    .getRepository(Asset)
    .findOne(req.body.asset, { relations: ['organization'] });
  if (!asset) {
    return res.status(404).json('Asset does not exist');
  }
  const hasAccess = await hasAssetWriteAccess(req, asset.id);
  if (!hasAccess) {
    return res.status(403).json('Authorization is required');
  }
  if (!req.body.testers) {
    return res.status(400).json('No testers have been selected');
  }
  const testers = await userController.getUsersById(req.body.testers);
  const assessment = new Assessment();
  assessment.asset = asset;
  assessment.name = req.body.name;
  assessment.executiveSummary = req.body.executiveSummary;
  assessment.jiraId = req.body.jiraId;
  assessment.testUrl = req.body.testUrl;
  assessment.prodUrl = req.body.prodUrl;
  assessment.scope = req.body.scope;
  assessment.tag = req.body.tag;
  assessment.startDate = new Date(req.body.startDate);
  assessment.endDate = new Date(req.body.endDate);
  assessment.testers = testers;
  const errors = await validate(assessment);
  if (errors.length > 0) {
    return res.status(400).send('Assessment form validation failed');
  } else {
    await getConnection().getRepository(Assessment).save(assessment);
    res.status(200).json('Assessment created succesfully');
  }
}
Example #4
Source File: users.controller.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@httpPut('/:userId', TYPES.FetchLoggedUserMiddleware)
  public async update(
    @requestParam('userId') userId: string,
    @requestBody() body: Partial<User>,
    req: Request & {user: User},
    res: Response,
  ) {
    if (Number(userId) !== req.user.id) {
      return res.sendStatus(403);
    }

    const repository = await this.databaseService.getRepository(UserRepository);
    req.user.email = body.email ?? req.user.email;
    req.user.password = body.password ?? req.user.password;

    const errors = await validate(req.user);

    if (errors.length !== 0) {
      return res.status(400).json({errors});
    }
    await repository.save(req.user);
    return res.sendStatus(204);
  }
Example #5
Source File: validation.pipe.ts    From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 6 votes vote down vote up
async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length) {
      console.log(this.formatErrors(errors));
      throw new HttpException(
        `Validation error :  ${this.formatErrors(errors)}`,
        HttpStatus.BAD_REQUEST,
      );
    }
    return value;
  }
Example #6
Source File: ClassValidator.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/ban-types
  public static async validate<TTarget extends object>(target: TTarget, context?: string): Promise<Optional<ClassValidationDetails>> {
    let details: Optional<ClassValidationDetails>;
    const errors: ValidationError[] = await validate(target);
    
    if (errors.length > 0) {
      details = {
        context: context || target.constructor.name,
        errors : []
      };
      for (const error of errors) {
        details.errors.push({
          property: error.property,
          message : error.constraints ? Object.values(error.constraints) : []
        });
      }
    }
    
    return details;
  }
Example #7
Source File: validation.pipe.ts    From nestjs-starter with MIT License 6 votes vote down vote up
async transform(value, metadata: ArgumentMetadata) {
    if (!value) {
      throw new BadRequestException('No data submitted');
    }

    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(this.buildError(errors), 'Input data validation failed');
    }
    return value;
  }
Example #8
Source File: form-validator.directive.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
   * Goes through all of the form and checks for any issues, updates all of the fields accordingly.
   */
  updateForm(): Promise<boolean> {
    return validate(this.appFormValidator).then((validationErrors) => {
      const prevIsFormValid = this._isFormValid;
      this._isFormValid = true;

      this.getFormGroupInputs().forEach((input: HTMLInputElement) => {
        const name = input.name;
        const validationError = this.getValidationErrorFromFieldName(
          name,
          validationErrors
        );
        this.updateFormField(input, validationError);

        if (validationError) this._isFormValid = false;
      });

      if (prevIsFormValid !== this._isFormValid)
        this.appFormValidatorIsFormValidChange.emit(this._isFormValid);

      return this._isFormValid;
    });
  }
Example #9
Source File: assessment.controller.ts    From bulwark with MIT License 6 votes vote down vote up
updateAssessmentById = async (req: UserRequest, res: Response) => {
  if (!req.params.assessmentId) {
    return res.status(400).send('Invalid assessment request');
  }
  if (isNaN(+req.params.assessmentId)) {
    return res.status(400).json('Invalid Assessment ID');
  }
  let assessment = await getConnection()
    .getRepository(Assessment)
    .findOne(req.params.assessmentId, { relations: ['testers', 'asset'] });
  if (!assessment) {
    return res.status(404).json('Assessment does not exist');
  }
  const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
  if (!hasAccess) {
    return res.status(403).json('Authorization is required');
  }
  if (!req.body.testers) {
    return res.status(400).json('No testers have been selected');
  }
  const assessmentId = assessment.id;
  delete req.body.asset;
  assessment = req.body;
  assessment.id = assessmentId;
  assessment.testers = await userController.getUsersById(req.body.testers);
  if (assessment.startDate > assessment.endDate) {
    return res
      .status(400)
      .send('The assessment start date can not be later than the end date');
  }
  const errors = await validate(assessment);
  if (errors.length > 0) {
    return res.status(400).send('Assessment form validation failed');
  } else {
    await getConnection().getRepository(Assessment).save(assessment);
    res.status(200).json('Assessment patched successfully');
  }
}
Example #10
Source File: object-validator.service.ts    From nest-amqp with MIT License 6 votes vote down vote up
/**
   * Transforme and validate a source object by a decorated class. It works with
   * the `class-validator` and the `class-transformer` packages.
   *
   * By default, the validator will strip every property that is not explicitly exposed
   *
   * @param {new (...params: unknown[]) => T} type Class with validation and transformation decorators.
   * @param {unknown} plain Source object which will be transformed and validated.
   * @param {ObjectValidationOptions} options Transformation and validations options.
   *
   * @return {Promise<T>} The transformed and validated object.
   *
   * {@link https://www.npmjs.com/package/class-transformer class-transformer}
   * {@link https://www.npmjs.com/package/class-validator class-validator}
   *
   * @public
   */
  public async validate<T>(type: new (...params: unknown[]) => T, plain: unknown, options?: ObjectValidationOptions): Promise<T> {
    if (plain === null || plain === undefined) {
      throw new ValidationNullObjectException(type.name);
    }

    const transformerOptions = options?.transformerOptions ?? {};
    const validatorOptions = options?.validatorOptions ?? {};

    const object: T = plainToClass<T, unknown>(type, plain, { strategy: 'excludeAll', ...transformerOptions });

    const errors = await validate(object as any, validatorOptions);

    if (errors.length !== 0) {
      throw new ValidationException(errors);
    }

    return object;
  }
Example #11
Source File: products.controller.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@httpPost('/', TYPES.FetchLoggedUserMiddleware)
  public async create(
    @requestBody() body: Partial<Product>,
    req: Request & {user: User},
    res: Response,
  ) {
    const repository = await this.databaseService.getRepository(
      ProductRepository,
    );
    const product = new Product();
    product.title = body.title;
    product.published = body.published;
    product.price = Number(body.price);
    product.user = req.user;

    const errors = await validate(product);

    if (errors.length !== 0) {
      return res.status(400).json({errors});
    }

    await repository.save(product);
    return res.sendStatus(201);
  }
Example #12
Source File: ValidatorRequest.ts    From node-experience with MIT License 6 votes vote down vote up
static async handle(request: any)
    {
        const errors = await validate(request);

        if (!_.isEmpty(errors))
        {
            throw new ErrorHttpException(StatusCode.HTTP_UNPROCESSABLE_ENTITY, { message: 'Failed Request.' }, errors);
        }
    }
Example #13
Source File: student.routes.ts    From Typescript_TypeORM with Apache License 2.0 6 votes vote down vote up
studentRouter.post('/', async (request, response) => {
  try {
    const repo = getRepository(Student);
    const { key, name, email, discipline } = request.body;

    const student = repo.create({
      key,
      name,
      email,
      discipline,
    });

    const errors = await validate(student);

    if (errors.length === 0) {
      const res = await repo.save(student);
      return response.status(201).json(res);
    }
    return response.status(400).json(errors);
  } catch (err) {
    console.log('err.message :>> ', err.message);
    return response.status(400).send();
  }
});
Example #14
Source File: AuthController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static changePassword = async (req: Request, res: Response) => {
    //Get ID from JWT
    const id = res.locals.jwtPayload.userId;

    //Get parameters from the body
    const { oldPassword, newPassword } = req.body;
    if (!(oldPassword && newPassword)) {
      res.status(400).send();
      return;
    }

    const userRepository = getRepository(User);
    let user: User;
    try {
      user = await userRepository.findOneOrFail(id);
    } catch (id) {
      res.status(401).send();
      return;
    }

    if (!user.checkIfUnencryptedPasswordIsValid(oldPassword)) {
      res.status(401).send();
      return;
    }

    user.password = newPassword;
    const errors = await validate(user);
    if (errors.length > 0) {
      res.status(400).send(errors);
      return;
    }

    user.hashPassword();
    await userRepository.save(user);

    res.status(204).send();
  };
Example #15
Source File: write-events-prepublish.service.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
// transform to dto each event and validate it
  async validate(events: T[]) {
    let errors = [];
    for (const event of events) {
      this.logger.debug(`Validating ${event.constructor.name}`);
      // @todo JDM class-transformer is not converting data property !
      //    (metadata is working, so it might be related to inheritance)
      const validateEvent: any = plainToClass(event.constructor as any, event);
      errors = [...errors, ...(await validate(validateEvent))];
    }
    return errors;
  }
Example #16
Source File: UserController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static editUser = async (req: Request, res: Response) => {
    const id = req.params.id;

    const { username, role } = req.body;

    const userRepository = getRepository(User);
    let user;
    try {
      user = await userRepository.findOneOrFail(id);
    } catch (error) {
      res.status(404).send("User not found");
      return;
    }

    user.name = username;
    user.role = role;
    const errors = await validate(user);
    if (errors.length > 0) {
      res.status(400).send(errors);
      return;
    }

    try {
      await userRepository.save(user);
    } catch (e) {
      res.status(409).send("username already in use");
      return;
    }
    //After all send a 204 (no content, but accepted) response
    res.status(204).send();
  };
Example #17
Source File: local.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async validate(req: ExpressRequest, email: string, password: string): Promise<ValidateUserOutput> {
    const errors = await validate(new SignInDto(req.body));

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

    const user = await this.authService.validateUser(email, password);

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
Example #18
Source File: AuthController.ts    From mysql_node_angular with MIT License 6 votes vote down vote up
static changePassword = async (req: Request, res: Response) => {
    const { userId } = res.locals.jwtPayload;
    const { oldPassword, newPassword } = req.body;

    if (!(oldPassword && newPassword)) {
      res.status(400).json({ message: 'Old password & new password are required' });
    }

    const userRepository = getRepository(Users);
    let user: Users;

    try {
      user = await userRepository.findOneOrFail(userId);
    } catch (e) {
      res.status(400).json({ message: 'Somenthing goes wrong!' });
    }

    if (!user.checkPassword(oldPassword)) {
      return res.status(401).json({ message: 'Check your old Password' });
    }

    user.password = newPassword;
    const validationOps = { validationError: { target: false, value: false } };
    const errors = await validate(user, validationOps);

    if (errors.length > 0) {
      return res.status(400).json(errors);
    }

    // Hash password
    user.hashPassword();
    userRepository.save(user);

    res.json({ message: 'Password change!' });
  };
Example #19
Source File: products.controller.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@httpPut(
    '/:productId',
    TYPES.FetchLoggedUserMiddleware,
    TYPES.FetchProductMiddleware,
  )
  public async update(
    @requestBody() body: Partial<Product>,
    req: Request & {user: User; product: Product},
    res: Response,
  ) {
    if (!this.canEditProduct(req.user, req.product)) {
      return res.sendStatus(403);
    }

    req.product.title = body.title;
    req.product.published = body.published;
    req.product.price = Number(body.price);

    const errors = await validate(req.product);

    if (errors.length !== 0) {
      return res.status(400).json({errors});
    }
    const repository = await this.databaseService.getRepository(
      ProductRepository,
    );
    await repository.save(req.product);
    return res.sendStatus(204);
  }
Example #20
Source File: update-collection.dto.ts    From aqualink-app with MIT License 5 votes vote down vote up
@ApiProperty({ example: [1, 4, 5] })
  @IsOptional()
  @IsNumber({}, { each: true })
  @Validate(EntityExists, [Site], { each: true })
  removeSiteIds?: number[];
Example #21
Source File: data_source.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
@IsOptional()
    @Validate(DataRetentionDays)
    data_retention_days = 30;
Example #22
Source File: update-region.dto.ts    From aqualink-app with MIT License 5 votes vote down vote up
@ApiProperty({ example: 1 })
  @IsOptional()
  @IsInt()
  @Validate(EntityExists, [Region])
  readonly parentId?: number;
Example #23
Source File: environment.model.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
@IsOptional()
    @Validate(ServerConfigModel)
    public serverConfig?: ServerConfigModel;
Example #24
Source File: site-data.dto.ts    From aqualink-app with MIT License 5 votes vote down vote up
@ApiProperty({ example: 1 })
  @Type(() => Number)
  @IsNumber()
  @Validate(EntityExists, [Site])
  siteId: number;
Example #25
Source File: asset.controller.ts    From bulwark with MIT License 5 votes vote down vote up
addJiraIntegration = (
  username: string,
  host: string,
  apiKey: string,
  asset: Asset
): Promise<Jira> => {
  return new Promise(async (resolve, reject) => {
    const existingAsset = await getConnection()
      .getRepository(Asset)
      .findOne(asset.id);
    if (existingAsset.jira) {
      reject(
        `The Asset: ${existingAsset.name} contains an existing Jira integration.  Purge the existing Jira integration and try again.`
      );
      return;
    }
    const jiraInit: Jira = {
      id: null,
      username,
      host,
      asset,
      apiKey,
    };
    try {
      jiraInit.apiKey = encrypt(apiKey);
    } catch (err) {
      reject(err);
      return;
    }
    const errors = await validate(jiraInit);
    if (errors.length > 0) {
      reject('Jira integration requires username, host, and API key.');
      return;
    } else {
      const jiraResult = await getConnection()
        .getRepository(Jira)
        .save(jiraInit);
      resolve(jiraResult);
    }
  });
}
Example #26
Source File: DataHolderOidcResponse.ts    From ADR-Gateway with MIT License 5 votes vote down vote up
DataHolderOidcResponse = async (dhOidcResponse:DataholderOidcResponse) => {
  let errors = await validate(dhOidcResponse)
  if (errors.length > 0) throw errors; // TODO standardize Validate errors
  return true;
}
Example #27
Source File: ParametersValidator.ts    From affinidi-core-sdk with Apache License 2.0 5 votes vote down vote up
static async validate(schemas: any) {
    const allErrors: any = []

    for (const [index, schema] of schemas.entries()) {
      const { isArray, type, isRequired, value: SchemaValue } = schema

      let errors: any = []

      const isArrayValid = Array.isArray(SchemaValue) && SchemaValue

      if (isArray && isArrayValid && SchemaValue.length === 0) {
        continue
      }

      if (isArray && !isArrayValid) {
        const message = `Parameter at index [${index}] should be an array.`
        const error = { value: SchemaValue, message }

        allErrors.push(error)

        continue
      }

      if (isArray) {
        const items = SchemaValue

        for (const item of items) {
          errors = await ParametersValidator.process({ type, isRequired, value: item }, index)

          allErrors.push(...errors)
        }
      } else {
        errors = await ParametersValidator.process(schema, index)

        allErrors.push(...errors)
      }
    }

    if (allErrors.length > 0) {
      throw new SdkErrorFromCode('COR-1', { errors: allErrors })
    }
  }
Example #28
Source File: UserController.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static newUser = async (req: Request, res: Response) => {
    let username = req.body.user;
    let password = req.body.password;
    let role = req.body.role;

    //    console.log(req.body)

    if (isUndefined(username)) {
      res.status(400).send("user missing");
      return;
    }
    if (isUndefined(password)) {
      res.status(400).send("password missing");
      return;
    }
    if (isUndefined(role)) {
      res.status(400).send("role missing");
      return;
    }

    let user = new User();
    user.name = username;
    user.password = password;
    user.role = role;

    const errors = await validate(user);
    if (errors.length > 0) {
      res.status(400).send(errors);
      return;
    }

    user.hashPassword();

    const userRepository = getRepository(User);
    try {
      await userRepository.save(user);
    } catch (e) {
      res.status(409).send("Username already in use");
      return;
    }

    res.status(201).send("User created");
  };
Example #29
Source File: pipe-transtorm.ts    From malagu with MIT License 5 votes vote down vote up
public async transform(value: any, metadata: ArgumentMetadata): Promise<any> {
        const opts = this.options || {};
        const { argType } = metadata;
        if (!argType || !this.toValidate(metadata)) {
            return value;
        }
        const originalValue = value;
        value = this.toEmptyIfNil(value);

        const isNil = value !== originalValue;
        const isPrimitive = this.isPrimitive(value);
        this.stripProtoKeys(value);
        let entity = plainToInstance(
            argType,
            value,
            opts.transformOptions,
        );

        const originalEntity = entity;
        const isCtorNotEqual = entity.constructor !== argType;

        if (isCtorNotEqual && !isPrimitive) {
            entity.constructor = argType;
        } else if (isCtorNotEqual) {
            // when "entity" is a primitive value, we have to temporarily
            // replace the entity to perform the validation against the original
            // metatype defined inside the handler
            entity = { constructor: argType } as any;
        }

        const errors = await validate(entity, opts.validatorOptions);
        if (errors.length > 0) {
            throw new ValidationErrors(opts.detailedOutputDisabled ? undefined : errors);
        }
        if (isPrimitive) {
            // if the value is a primitive value and the validation process has been successfully completed
            // we have to revert the original value passed through the pipe
            entity = originalEntity;
        }
        if (opts.transformEnabled) {
            return entity;
        }
        if (isNil) {
            // if the value was originally undefined or null, revert it back
            return originalValue;
        }
        return Object.keys(opts.validatorOptions).length > 0
            ? instanceToPlain(entity, opts.transformOptions)
            : value;
    }