● バリデーション+クラス(型)の記述
A. class-validator
import { IsNotEmpty, IsEmail, Length } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty()
@Length(10, 20)
username: string;
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
}
B. zod
import { z } from 'zod';
export const CreateUserDtoSchema = z.object({
username: z.string().min(10).max(20),
email: z.string().email(),
password: z.string().nonempty(),
});
export type CreateUserDto = z.infer<typeof CreateUserDtoSchema>;
● バリデーションの実行
A. class-validator
import { IsNotEmpty, IsEmail, Length, validateOrReject } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty()
@Length(10, 20)
username: string;
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
constructor(username: string, email: string, password: string) {
this.username = username;
this.email = email;
this.password = password;
validateOrReject(this).catch(errors => {
console.error('Validation failed:', errors);
throw errors;
});
}
}
B. zod
import { z } from 'zod';
const CreateUserDtoSchema = z.object({
username: z.string().min(10).max(20),
email: z.string().email(),
password: z.string().nonempty(),
});
export class CreateUserDto {
username: string;
email: string;
password: string;
constructor(username: string, email: string, password: string) {
const parsedData = CreateUserDtoSchema.parse({ username, email, password });
this.username = parsedData.username;
this.email = parsedData.email;
this.password = parsedData.password;
}
}