How to use class-validator - 10 common examples

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 ZhiXiao-Lin / nestify / server / src / common / dtos / login.dto.ts View on Github external
import { IsMobilePhone, MinLength, MaxLength, IsNotEmpty } from 'class-validator';
import { ApiModelProperty } from '@nestjs/swagger';

export class LoginDto {
	@ApiModelProperty()
	// @IsMobilePhone('zh-CN', {
	// 	message: '手机号无效'
	// })
	@IsNotEmpty({
		message: '帐号不能为空'
	})
	readonly account: string;

	@ApiModelProperty()
	@MinLength(8, {
		message: '密码不能少于8位'
	})
	@MaxLength(12, {
		message: '密码不能大于12位'
	})
	@IsNotEmpty({
		message: '密码不能为空'
	})
	readonly password: string;
}
github xmlking / ngx-starter-kit / apps / api / src / app / project / dto / resource-quota.ts View on Github external
// namespace level hard limits
export class ResourceQuota implements IResourceQuota {
  @IsNotEmpty()
  @ValidateNested()
  @Type(() => Requests)
  requests: Requests;

  @IsNotEmpty()
  @ValidateNested()
  @Type(() => Limits)
  limits: Limits;

  @IsOptional()
  @IsNumber()
  @Min(0)
  @Max(10156)
  cpu ? = 1;

  @IsOptional()
  @IsNumber()
  @Min(0)
  @Max(10720)
  memory ? = 1;
}
github goldcaddy77 / warthog-starter / src / project / project.model.ts View on Github external
import { Environment } from '../environment/environment.model';
import { FeatureFlagSegment } from '../feature-flag-segment/feature-flag-segment.model';
import { FeatureFlagUser } from '../feature-flag-user/feature-flag-user.model';
import { FeatureFlag } from '../feature-flag/feature-flag.model';
import { Segment } from '../segment/segment.model';
import { UserSegment } from '../user-segment/user-segment.model';

import { Matches } from 'class-validator';

@Model()
export class Project extends BaseModel {
  @StringField({ maxLength: 50, minLength: 3, nullable: false })
  name!: string;

  @Matches(/^[a-z0-9]+(-[a-z0-9]+)*$/) // Lowercase sluggified string
  @StringField({ maxLength: 20, minLength: 3, nullable: false, unique: true })
  key!: string;

  @OneToMany(() => Environment, (environment: Environment) => environment.project)
  environments?: Environment[];

  @OneToMany(() => Segment, (segment: Segment) => segment.project)
  segments?: Segment[];

  @OneToMany(() => FeatureFlag, (featureFlag: FeatureFlag) => featureFlag.project)
  featureFlags?: FeatureFlag[];

  @OneToMany(() => FeatureFlagUser, (featureFlagUser: FeatureFlagUser) => featureFlagUser.project)
  featureFlagUsers?: FeatureFlagUser[];

  @OneToMany(
github ahmetuysal / nest-hackathon-starter / src / contract / request / signup-request.model.ts View on Github external
@ApiModelProperty()
  @IsNotEmpty()
  // alphanumeric characters and - are valid
  // you can change this as you like
  @Matches(RegExp('^[a-zA-Z0-9\\-]+$'))
  @MaxLength(20)
  username: string;

  @ApiModelProperty()
  @IsNotEmpty()
  @MinLength(8)
  password: string;

  @ApiModelProperty()
  @IsNotEmpty()
  @Matches(RegExp('^[A-Za-zıöüçğşİÖÜÇĞŞñÑáéíóúÁÉÍÓÚ ]+$'))
  @MaxLength(20)
  firstName: string;

  @ApiModelProperty()
  @IsNotEmpty()
  @Matches(RegExp('^[A-Za-zıöüçğşİÖÜÇĞŞñÑáéíóúÁÉÍÓÚ ]+$'))
  @MaxLength(20)
  lastName: string;

  @ApiModelProperty()
  @IsOptional()
  @IsNotEmpty()
  @Matches(RegExp('^[A-Za-zıöüçğşİÖÜÇĞŞñÑáéíóúÁÉÍÓÚ ]+$'))
  @MaxLength(20)
  middleName?: string;
}
github NationalBankBelgium / stark / packages / stark-core / src / validation / validators / array-size-range / array-size-range.validator.fn.ts View on Github external
export function starkArraySizeRange(array: any[], minSize?: number, maxSize?: number): boolean {
	// by default, if the requested validator class is not already registered in the container from the 'class-validator' container
	// then it will registered automatically so it will indeed be a singleton
	// IMPORTANT: the StarkValidatorImpl should be used in the same way wherever needed to avoid instantiating it multiple times!
	const validator = getFromContainer(Validator);
	let isValid = true;

	if (typeof minSize !== "undefined") {
		isValid = isValid && validator.arrayMinSize(array, minSize);
	}
	if (typeof maxSize !== "undefined") {
		isValid = isValid && validator.arrayMaxSize(array, maxSize);
	}
	return isValid;
}
github epiphone / routing-controllers-openapi / sample / 01-basic / app.ts View on Github external
import {
  createExpressServer,
  getMetadataArgsStorage
} from 'routing-controllers'
import { routingControllersToSpec } from 'routing-controllers-openapi'

import { UsersController } from './UsersController'

const routingControllersOptions = {
  controllers: [UsersController],
  routePrefix: '/api'
}
const app: Express = createExpressServer(routingControllersOptions)

// Parse class-validator classes into JSON Schema:
const metadatas = (getFromContainer(MetadataStorage) as any).validationMetadatas
const schemas = validationMetadatasToSchemas(metadatas, {
  refPointerPrefix: '#/components/schemas/'
})

// Parse routing-controllers classes into OpenAPI spec:
const storage = getMetadataArgsStorage()
const spec = routingControllersToSpec(storage, routingControllersOptions, {
  components: {
    schemas,
    securitySchemes: {
      basicAuth: {
        scheme: 'basic',
        type: 'http'
      }
    }
  },
github vladimiry / ElectronMail / src / electron-main / database / entity / mail.ts View on Github external
@ValidateNested()
    @IsArray()
    @Type(() => MailAddress)
    bccRecipients!: MailAddress[];

    @ValidateNested()
    @IsArray()
    @Type(() => File)
    attachments!: File[];

    @IsNotEmpty()
    @IsBoolean()
    unread!: Model.Mail["unread"];

    @IsIn(Model.MAIL_STATE._.values)
    state!: Model.Mail["state"];

    // TODO consider making Mail.confidential field optional, not used by protonmail?
    @IsNotEmpty()
    @IsBoolean()
    confidential!: Model.Mail["confidential"];

    @IsIn(Model.REPLY_TYPE._.values)
    replyType!: Model.Mail["replyType"];

    @ValidateNested()
    @Type(() => MailFailedDownload)
    failedDownload?: MailFailedDownload;
}
github kazekyo / nestjs-graphql-relay / src / common / connection-paging.ts View on Github external
@Field(type => String, {
    nullable: true,
    description: 'Paginate before opaque cursor',
  })
  @ValidateIf(o => o.before !== undefined)
  @Validate(CannotUseWithout, ['last'])
  @Validate(CannotUseWith, ['after', 'first'])
  before?: Relay.ConnectionCursor;

  @Field(type => String, {
    nullable: true,
    description: 'Paginate after opaque cursor',
  })
  @ValidateIf(o => o.after !== undefined)
  @Validate(CannotUseWithout, ['first'])
  @Validate(CannotUseWith, ['before', 'last'])
  after?: Relay.ConnectionCursor;

  @Field(type => Int, { nullable: true, description: 'Paginate first' })
  @ValidateIf(o => o.first !== undefined)
  @Min(1)
  @Validate(CannotUseWith, ['before', 'last'])
  first?: number;

  @Field(type => Int, { nullable: true, description: 'Paginate last' })
  @ValidateIf(o => o.last !== undefined)
  // Required `before`. This is a weird corner case.
  // We'd have to invert the ordering of query to get the last few items then re-invert it when emitting the results.
  // We'll just ignore it for now.
  @Validate(CannotUseWithout, ['before'])
  @Validate(CannotUseWith, ['after', 'first'])
  @Min(1)
github goparrot / geocoder / src / util / world-country-state / world-country-state-util.ts View on Github external
static async find(_query: WorldCountryStateQueryInterface): Promise {
        const query: WorldCountryStateQuery = plainToClass(WorldCountryStateQuery, _query);

        // clear undefined/empty values
        for (const key of Object.keys(query)) {
            if (!query[key]) {
                delete query[key];
            }
        }

        try {
            await validateOrReject(query, {
                whitelist: true,
                forbidNonWhitelisted: true,
                validationError: { target: false, value: false },
            });
        } catch (err) {
            return;
        }

        const stateData: WorldCountryStateInterface | undefined = (countryStates as WorldCountryStateInterface[]).find(
            (plainState: WorldCountryStateInterface) => {
                const state: WorldCountryState = plainToClass(WorldCountryState, plainState);

                return WorldCountryStateUtil.match(state, query);
            },
        );