class-validator#ValidatorConstraintInterface TypeScript Examples

The following examples show how to use class-validator#ValidatorConstraintInterface. 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: match.ts    From node-experience with MIT License 6 votes vote down vote up
@ValidatorConstraint({ name: 'Match' })
export class MatchConstraint implements ValidatorConstraintInterface
{
    validate(value: any, args: ValidationArguments)
    {
        const [relatedPropertyName] = args.constraints;
        const relatedValue = (args.object as any)[relatedPropertyName];
        return value === relatedValue;
    }
}
Example #2
Source File: unique.validator.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@ValidatorConstraint({ async: true })
export class UniqueTitleConstrainsts implements ValidatorConstraintInterface {
  constructor() {}

  async validate(title: string, args: ValidationArguments): Promise<boolean> {
    const postRepo: Repository<PostEntity> = await (
      await import('../posts.entity')
    ).default;

    return !!!(await postRepo.findOne({ where: { title } }));
  }
}
Example #3
Source File: applicationScope.validator.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
 * Validator for Strings containing scope strings
 */
@ValidatorConstraint({ name: 'ApplicationScopes', async: false })
export class ApplicationScopes implements ValidatorConstraintInterface {
  validate(scopes: string) {
    try {
      const validScopes = ['name', 'registrationNumber', 'github', 'twitter', 'linkedIn', 'previousEvents'];
      const decodedString = decodeURI(scopes);
      decodedString.split(' ').forEach((str) => {
        if (!validScopes.includes(str)) {
          throw new Error('invalid scope');
        }
      });
      return true;
    } catch (e) {
      return false;
    }
  }

  defaultMessage() {
    return 'Invalid application scopes';
  }
}
Example #4
Source File: registrationNumber.validator.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
 * Validator for Registration Number as a decorator
 */
@ValidatorConstraint({ name: 'RegistrationNumber', async: false })
export class RegistrationNumber implements ValidatorConstraintInterface {
  validate(reg: string) {
    try {
      const instance = new RegistrationValidator(reg);
      return instance !== undefined;
    } catch (e) {
      return false;
    }
  }

  defaultMessage() {
    return 'Invalid Registration Nuber';
  }
}
Example #5
Source File: user.inputs.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@ValidatorConstraint({ name: "validateColor", async: false })
class ValidateColor implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    return !isColorTooDark(text);
  }

  defaultMessage(args: ValidationArguments) {
    return "Color value ($value) is too dark";
  }
}
Example #6
Source File: IsEntity.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ValidatorConstraint({ async: true })
export class IsEntityConstraint implements ValidatorConstraintInterface {
  constructor(private readonly connection: Connection) {}

  getEntity(entity, property, value) {
    try {
      return this.connection.manager
        .createQueryBuilder(entity, 'target')
        .where(`LOWER(${property}) = LOWER(:value)`, { value })
        .getOne()
    } catch (error) {
      console.log(error) // eslint-disable-line no-console

      return null
    }
  }

  async validate(value: any, args: any) {
    const [options, check] = args.constraints

    const entity = options instanceof Function ? options : options.entity

    const result = await this.getEntity(entity, options.field || args.property, value)

    return check === !!result
  }
}
Example #7
Source File: data_retention_validator.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
@ValidatorConstraint({ name: 'dataRetentionDays', async: false })
export class DataRetentionDays implements ValidatorConstraintInterface {
    validate(v: number) {
        return typeof v === 'number' && v >= -1  // for async validations you must return a Promise<boolean> here
    }

    defaultMessage(args: ValidationArguments) {
        // here you can provide default error message if validation failed
        return 'Data Retention must be an integer greater than or equal to -1';
    }
}
Example #8
Source File: is-email-already-exist.validator.ts    From nestjs-starter with MIT License 6 votes vote down vote up
@ValidatorConstraint({ async: true })
export class IsEmailAlreadyExistConstraint implements ValidatorConstraintInterface {
  async validate(email: any) {
    const query = getRepository<User>(User).createQueryBuilder().where('email = :email', { email });
    const result = await query.getOne(); // return true if user exists
    if (result) return false;
    return true;
  }
}
Example #9
Source File: is-username-already-exist.validator.ts    From nestjs-starter with MIT License 6 votes vote down vote up
@ValidatorConstraint({ async: true })
export class IsUsernameAlreadyExistConstraint implements ValidatorConstraintInterface {
  async validate(username: any) {
    const query = getRepository<User>(User).createQueryBuilder().where('username = :username', { username });
    const result = await query.getOne(); // return true if user exists
    if (result) return false;
    return true;
  }
}
Example #10
Source File: SignatureIdValidator.ts    From tatum-blockchain-connector with MIT License 6 votes vote down vote up
@ValidatorConstraint({name: 'signatureId', async: false})
export class SignatureIdValidator implements ValidatorConstraintInterface {
    public defaultMessage(validationArguments?: ValidationArguments) {
        return 'Either signatureId, or privateKey/fromPrivateKey must be present.';
    }

    public validate(value: any, validationArguments?: ValidationArguments) {
        const data = validationArguments?.object as any;
        if (data.fromPrivateKey && data.signatureId) {
            return false;
        }
        if (data.privateKey && data.signatureId) {
            return false;
        }
        return true;
    }

}
Example #11
Source File: IsFieldEqual.ts    From test with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ValidatorConstraint({ async: false })
export class IsFieldEqualConstraint implements ValidatorConstraintInterface {
  async validate(value: string, args: ValidationArguments) {
    const [target] = args.constraints

    return value === args.object[target]
  }
}