class-validator#validateSync TypeScript Examples

The following examples show how to use class-validator#validateSync. 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: domain-validator.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
/**
   * Throw ValidationError if model is not valid.
   * @throws ValidationError
   */
  validate(): void {
    const errors = validateSync(this);

    if (errors.length) {
      throw errors;
    }
  }
Example #2
Source File: form.ts    From tezos-academy with MIT License 6 votes vote down vote up
updateFormFromChange = (
  event: ChangeEvent<HTMLInputElement>,
  form: FormInputs,
  FormInputClass: any,
): FormInputs => {
  event.persist()

  const updatedForm: FormInputs = {
    ...form,
    [event.target.name]: {
      value: event.target.value,
    },
  }

  let formInputs: any = new FormInputClass() as any

  for (var key in updatedForm) {
    if (updatedForm.hasOwnProperty(key)) {
      formInputs[key] = updatedForm[key].value
    }
  }

  validateSync(formInputs).forEach((error: ValidationError) => {
    const firstConstraint = error && error.constraints
    if (firstConstraint && updatedForm[error.property])
      updatedForm[error.property].error = firstConstraint[Object.keys(firstConstraint)[0]]
  })

  return updatedForm
}
Example #3
Source File: form.ts    From tezos-academy with MIT License 6 votes vote down vote up
updateFormFromSubmit = (
  event: SyntheticEvent,
  form: FormInputs,
  FormInputClass: any,
): FormInputs => {
  event.preventDefault()

  const updatedForm: FormInputs = JSON.parse(JSON.stringify(form))

  let formInputs: any = new FormInputClass() as any

  for (var key in updatedForm) {
    updatedForm[key].blurred = true
    if (updatedForm.hasOwnProperty(key)) {
      formInputs[key] = updatedForm[key].value
    }
  }

  validateSync(formInputs).forEach((error: ValidationError) => {
    const firstConstraint = error && error.constraints
    if (firstConstraint && updatedForm[error.property])
      updatedForm[error.property].error = firstConstraint[Object.keys(firstConstraint)[0]]
  })

  return updatedForm
}
Example #4
Source File: setup.ts    From epicgames-freegames-node with MIT License 5 votes vote down vote up
errors = validateSync(config, {
  validationError: {
    target: false,
  },
})
Example #5
Source File: model.abstract.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
private validate(): void {
        const errors = validateSync(this);

        if (arrayHasItems(errors)) {
            throw new ValidationFailureError(`${this.constructor.name} validation failure`, errors);
        }
    }
Example #6
Source File: DataFunction.ts    From remix-hexagonal-architecture with MIT License 4 votes vote down vote up
DataFunction =
  (errorFormatter = new DefaultErrorFormatter()): MethodDecorator =>
  (
    target: Object,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ) => {
    const originalMethod = descriptor.value;
    const bodyParameterIndex = Reflect.getOwnMetadata(
      METADATA_BODY,
      target,
      propertyKey
    );
    const paramsParameterIndex = Reflect.getOwnMetadata(
      METADATA_PARAMS,
      target,
      propertyKey
    );
    const queryParameterIndex = Reflect.getOwnMetadata(
      METADATA_QUERY,
      target,
      propertyKey
    );
    const ParamTypes = Reflect.getMetadata(
      "design:paramtypes",
      target,
      propertyKey
    );

    async function parseBody(args: DataFunctionArgs) {
      const formData = await args.request.formData();
      const body = plainToClass<any, any>(
        ParamTypes[bodyParameterIndex],
        Object.fromEntries(formData.entries())
      );
      const validationErrors = validateSync(body);

      if (validationErrors.length > 0) {
        throw new DecoratorValidationError(
          "Body validation failed",
          validationErrors
        );
      }

      return body;
    }

    async function parseParams(args: DataFunctionArgs) {
      const params = plainToClass<any, any>(
        ParamTypes[paramsParameterIndex],
        args.params
      );
      const validationErrors = validateSync(params);

      if (validationErrors.length > 0) {
        throw new Response(null, { status: 400 });
      }

      return params;
    }

    async function parseQuery(args: DataFunctionArgs) {
      const searchParams = new URL(args.request.url).searchParams;
      const query = plainToClass<any, any>(
        ParamTypes[queryParameterIndex],
        Object.fromEntries(searchParams.entries())
      );
      const validationErrors = validateSync(query);

      if (validationErrors.length > 0) {
        throw new Response(null, { status: 400 });
      }

      return query;
    }

    descriptor.value = async function (args: DataFunctionArgs) {
      const newArgs: any[] = [];

      try {
        if (bodyParameterIndex != null)
          newArgs[bodyParameterIndex] = await parseBody(args);
        if (paramsParameterIndex != null)
          newArgs[paramsParameterIndex] = await parseParams(args);
        if (queryParameterIndex != null)
          newArgs[queryParameterIndex] = await parseQuery(args);
      } catch (e) {
        if (!(e instanceof DecoratorValidationError)) throw e;

        return {
          errors: errorFormatter.format(e.validationErrors),
        };
      }

      newArgs.push(args);

      return originalMethod.apply(this, newArgs);
    };
  }