class-validator#ValidationError TypeScript Examples

The following examples show how to use class-validator#ValidationError. 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: shared-utils.ts    From nestjs-angular-starter with MIT License 7 votes vote down vote up
/**
 * Returns a textual presentation of a validation error.
 * @param error
 */
export function getTextualValidationError(error: ValidationError): string {
  let output = `${error.property}:\n`;

  if (error.constraints) {
    Object.keys(error.constraints).forEach((constraint) => {
      output += '- ' + error.constraints[constraint] + '\n';
    });
  }

  if (error.children && error.children.length > 0) {
    for (const child of error.children)
      output += this.getTextualValidationError(child) + '\n';
  }

  return output;
}
Example #2
Source File: shared-utils.ts    From nestjs-angular-starter with MIT License 7 votes vote down vote up
/**
 * Returns a textual presentation of ValidationErrors array detected with the class-validator library.
 * @param errors
 */
export function getFormValidationErrorText(
  errors: Array<ValidationError>
): string {
  let output = `Supplied form is invalid, please fix the following issues:\n`;
  errors
    .map((issue) => getTextualValidationError(issue))
    .forEach((issueStr) => (output += issueStr));

  return output;
}
Example #3
Source File: firstError.spec.ts    From tezos-academy with MIT License 6 votes vote down vote up
describe('Helper', () => {
  it('bypass if no validation error', () => {
    firstError([] as ValidationError[])
  })

  it('throws error the first validation error', () => {
    try {
      firstError(mockErrors as ValidationError[])
    } catch (error) {
      expect(error).toBeDefined()
      expect(error.message).toBe('usernameOrEmail must be longer than or equal to 2 characters')
    }
  })
})
Example #4
Source File: form-validator.directive.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
   * Updates a specific element state according to it's validation error.
   * @param el
   * @param error
   */
  updateFormField(el: HTMLInputElement, error?: ValidationError): void {
    const name = el.name;

    // Check if this fields has been written, if not don't update it's validation state until it is
    if (!this.appFormValidatorForce && !this.fieldsWritten[name]) return;
    el.classList.remove('is-valid', 'is-invalid');
    el.classList.add(error ? 'is-invalid' : 'is-valid');

    // If we don't want to show any validation error text
    if (this.appFormValidatorHideErrorText) return;
    const validationDesc = el.nextElementSibling;

    if (validationDesc) {
      validationDesc.classList.remove('invalid-feedback', 'valid-feedback');
      validationDesc.classList.add(
        error ? 'invalid-feedback' : 'valid-feedback'
      );
      validationDesc.innerHTML = null;

      if (error) {
        let errHTML = `<ul>`;
        for (const key of Object.keys(error.constraints)) {
          const constraint = error.constraints[key];
          errHTML += `<li>${constraint}</li>`;
        }

        errHTML += `</ul>`;
        validationDesc.innerHTML = errHTML;
      }
    }
  }
Example #5
Source File: form-validator.directive.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
private getValidationErrorFromFieldName(
    name: string,
    validationErrors: ValidationError[]
  ): ValidationError {
    let lastValidationError: ValidationError = null;

    // We split using '-' which represents a deeper property
    const split = name.split('-');

    // eslint-disable-next-line no-constant-condition
    while (true) {
      const property = split.shift();

      if (lastValidationError)
        lastValidationError = lastValidationError.children.find(
          (v) => v.property === property
        );
      else
        lastValidationError = validationErrors.find(
          (v) => v.property === property
        );

      // If no validation error was found, return null
      if (!lastValidationError) return;

      // Update the last validation error

      // If it's the end of the field name, return the validation error
      if (split.length === 0) return lastValidationError;
    }
  }
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: bad-request.filter.ts    From bank-server with MIT License 6 votes vote down vote up
private _validationFilter(validationErrors: ValidationError[]) {
        for (const validationError of validationErrors) {
            for (const [constraintKey, constraint] of Object.entries(
                validationError.constraints,
            )) {
                if (!constraint) {
                    // convert error message to error.fields.{key} syntax for i18n translation
                    validationError.constraints[constraintKey] =
                        'error.fields.' + _.snakeCase(constraintKey);
                }
            }
            if (!_.isEmpty(validationError.children)) {
                this._validationFilter(validationError.children);
            }
        }
    }
Example #8
Source File: bad-request.filter.ts    From bank-server with MIT License 6 votes vote down vote up
catch(exception: BadRequestException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        let statusCode = exception.getStatus();
        const r = <any>exception.getResponse();

        if (_.isArray(r.message) && r.message[0] instanceof ValidationError) {
            statusCode = HttpStatus.UNPROCESSABLE_ENTITY;
            const validationErrors = <ValidationError[]>r.message;
            this._validationFilter(validationErrors);
        }

        r.statusCode = statusCode;
        r.error = STATUS_CODES[statusCode];

        response.status(statusCode).json(r);
    }
Example #9
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 #10
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 #11
Source File: getClassValidatorError.ts    From next-api-decorators with MIT License 6 votes vote down vote up
function prependConstraintsWithParentProp(parentPath: string, error: ValidationError): ValidationError {
  const constraints: Record<string, any> = {};
  for (const key in error.constraints) {
    constraints[key] = `${parentPath}.${error.constraints[key]}`;
  }
  return {
    ...error,
    constraints
  };
}
Example #12
Source File: validation-failure.error.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
constructor(message: string, errors: ValidationError[] = []) {
        super(
            `${message}:\n\n${join(
                map(
                    errors,
                    ({property, constraints}) =>
                        `- Property "${property}" failed the following constraints: ${join(values(constraints), ', ')}`,
                ),
                '\n',
            )}`,
        );
    }
Example #13
Source File: user.validator.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
validate(): void {
    super.validate();

    // Cannot remove an role that's not in the set
    if (!this.roles.has(this.roleId)) {
      const error = new ValidationError();

      error.target = this;
      error.property = nameof<UserRoleRemoveValidator>(u => u.roleId);
      error.value = this.roleId;
      error.constraints = { isRoleExists: `${nameof<UserRoleRemoveValidator>(u => u.roleId)} does not exists for User` };
      error.children = [];

      throw error;
    }
  }
Example #14
Source File: user.validator.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
validate(): void {
    super.validate();

    // Cannot add an role that's already in the set
    if (this.roles.has(this.roleId)) {
      const error = new ValidationError();

      error.target = this;
      error.property = nameof<UserRoleAddValidator>(u => u.roleId);
      error.value = this.roleId;
      error.constraints = { isRoleNotExists: `${nameof<UserRoleAddValidator>(u => u.roleId)} already exists for User` };
      error.children = [];

      throw error;
    }
  }
Example #15
Source File: getClassValidatorError.ts    From next-api-decorators with MIT License 6 votes vote down vote up
function mapChildrenToValidationErrors(error: ValidationError, parentPath?: string): ValidationError[] {
  if (!(error.children && error.children.length)) {
    return [error];
  }
  const validationErrors = [];
  parentPath = parentPath ? `${parentPath}.${error.property}` : error.property;
  for (const item of error.children) {
    if (item.children && item.children.length) {
      validationErrors.push(...mapChildrenToValidationErrors(item, parentPath));
    }
    validationErrors.push(prependConstraintsWithParentProp(parentPath, item));
  }
  return validationErrors;
}
Example #16
Source File: DataFunction.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
format(errors: ValidationError[]): Record<string, string> {
    const formatted: Record<string, string> = {};

    for (let validationError of errors) {
      const constraints = validationError.constraints;
      if (!constraints) continue;

      const [, message] = Object.entries(constraints)[0];

      formatted[validationError.property] = message;
    }

    return formatted;
  }
Example #17
Source File: object-validator.service.ts    From nest-amqp with MIT License 6 votes vote down vote up
/**
   * Validate and transform a list of objects 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[]} plains Source array of object which will be transformed and validated.
   * @param {ObjectValidationOptions} options Transformation and validations options.
   *
   * @return {Promise<T[]>} Validated and transformed array.
   *
   * {@link https://www.npmjs.com/package/class-transformer class-transformer}
   * {@link https://www.npmjs.com/package/class-validator class-validator}
   *
   * @public
   */
  public async validateArray<T>(type: new (...params: unknown[]) => T, plains: unknown[], options?: ObjectValidationOptions): Promise<T[]> {
    if (plains === null || plains === undefined) {
      throw new ValidationNullObjectException(type.name);
    }

    const transformerOptions = options?.transformerOptions ?? {};
    const validatorOptions = options?.validatorOptions ?? {};
    const objects: T[] = plainToClass<T, unknown>(type, plains, { strategy: 'excludeAll', ...transformerOptions });
    const errors: ValidationError[] = [];

    for (const object of objects) {
      errors.push(...(await validate(object as any, validatorOptions)));
    }

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

    return objects;
  }
Example #18
Source File: ValidationModel.ts    From node-experience with MIT License 6 votes vote down vote up
constructor(errors: ValidationError)
    {
        this.property = errors.property;
        this.constraints = errors.constraints;

        if (!_.isEmpty(errors.children))
        {
            this.children = [];
            errors.children.forEach(_children => this.children.push(new ValidationModel(_children)));
        }
    }
Example #19
Source File: ErrorHttpException.ts    From node-experience with MIT License 6 votes vote down vote up
constructor(statusCode: IStatusCode = StatusCode.HTTP_INTERNAL_SERVER_ERROR, errorMessage: IErrorMessage  = { message: 'Internal Error' }, errors: ValidationError[] = [],  metadata: Record<string, any> = {})
    {
        super();
        this._statusCode = statusCode;
        this._errors = errors;
        this.message = errorMessage?.message;
        this._errorCode = errorMessage?.errorCode ?? null;
        this._metadata = metadata;
    }
Example #20
Source File: validation.exception.ts    From nest-amqp with MIT License 5 votes vote down vote up
constructor(errors: ValidationError[]) {
    super(JSON.stringify(errors));
  }
Example #21
Source File: getClassValidatorError.ts    From next-api-decorators with MIT License 5 votes vote down vote up
export function flattenValidationErrors(validationErrors: ValidationError[]): string[] {
  return validationErrors
    .flatMap(error => mapChildrenToValidationErrors(error))
    .filter((item: ValidationError) => !!item.constraints)
    .flatMap((item: ValidationError) => Object.values(item.constraints ?? {}));
}
Example #22
Source File: ErrorHandlerMiddleware.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
     * Error handler - sets response code and sends json with error message.
     * Handle: standard node error, HttpError, ValidationError and string.
     *
     * @param {any} error An throwed object (error)
     * @param {express.Request} req The Express request object
     * @param {express.Response} res The Express response object
     * @param {express.NextFunction} next The next Express middleware function
     */
    public error(error: any, _req: express.Request, res: express.Response, _next: express.NextFunction): void {
        const responseObject = {} as any;

        // if its an array of ValidationError
        // console.log(error);
        // console.log(Array.isArray(error));
        if (error && Array.isArray(error.errors) && error.errors.every((element) => element instanceof ValidationError)) {
            res.status(422);
            console.log('Inside');
            responseObject.message = "You have an error in your request's body. Check 'errors' field for more details!";
            // responseObject.errors = error;
            responseObject.status = 0;
            responseObject.data = {};
            responseObject.data.message = [];
            error.errors.forEach((element: ValidationError) => {
                Object.keys(element.constraints).forEach((type) => {
                    responseObject.data.message.push(`property ${element.constraints[type]}`);
                });
            });
        } else {
            // set http status
            if (error instanceof HttpError && error.httpCode) {
                res.status(error.httpCode);
            } else {
                res.status(500);
            }

            if (error instanceof Error) {
                const developmentMode: boolean = !this.isProduction;

                // set response error fields
                if (error.name && (developmentMode || error.message)) { // show name only if in development mode and if error message exist too
                    responseObject.name = error.name;
                }
                switch (error.name) {
                    case 'AuthorizationRequiredError':
                        responseObject.message = 'Unauthorized';
                        break;
                    default:
                        responseObject.message = error.message;
                        break;
                }

                if (error.stack && developmentMode) {
                    responseObject.stack = error.stack;
                }
            } else if (typeof error === 'string') {
                responseObject.message = error;
            }
        }

        if (this.isProduction) {
            this.log.error(error.name, error.message);
        } else {
            this.log.error(error.name, error.stack);
        }

        // send json only with error
       res.json(responseObject);
    }
Example #23
Source File: firstError.ts    From tezos-academy with MIT License 5 votes vote down vote up
firstError = (errors: ValidationError[]): void => {
  const firstConstraint = errors[0] && errors[0].constraints
  if (firstConstraint) throw new ResponseError(400, firstConstraint[Object.keys(firstConstraint)[0]])
}
Example #24
Source File: validation-errors.ts    From malagu with MIT License 5 votes vote down vote up
constructor(errors?: ValidationError[]) {
        super(errors === undefined ? undefined : JSON.stringify(errors));
    }
Example #25
Source File: DataFunction.ts    From remix-hexagonal-architecture with MIT License 5 votes vote down vote up
constructor(message: string, public validationErrors: ValidationError[]) {
    super(message);
  }
Example #26
Source File: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 5 votes vote down vote up
function formatValidationErrors(errors: ValidationError[]): ValidationErrorLog[] {
    return errors.map(error => ({
        property: error.property,
        constraints: error.constraints,
        children: error.children?.length > 0 ? formatValidationErrors(error.children) : undefined,
    }));
}
Example #27
Source File: ErrorHttpException.ts    From node-experience with MIT License 5 votes vote down vote up
private _errors: ValidationError[];