I want to combine multiple classes for reusability and consistency amongst backend and frontend. Something like:
import {
IsEmail,
IsString,
MaxLength,
MinLength,
validateSync
} from "class-validator";
class UserUsername {
@IsString()
@MinLength(3)
@MaxLength(10)
username!: string;
}
class UserEmail {
@IsEmail()
email!: string;
}
class UserPassword {
@IsString()
@MinLength(8)
password!: string;
}
class UserSecret {
@IsString()
secret!: string;
}
class User /* extends UserEmail, UserUsername, UserSecret */ {}
class UserDto /* extends UserEmail, UserUsername, UserPassword */ {}
const userDto = new UserDto();
userDto.username = "noerror";
userDto.email = "error";
userDto.password = "error";
console.log(validateSync(userDto).toString());
Is something similar anyway possible?
Note: I do not mean types only like TypeScript's &. The main purpose is to reuse class validation.
The Problem:
export class User {
@IsUUID()
id!: string;
@IsNotEmpty()
@IsString()
@MinLength(3)
username!: string;
@IsEmail()
email!: string;
@IsNotEmpty()
@IsString()
secret!: string;
@IsNotEmpty()
@IsAlpha()
firstName!: string;
@IsNotEmpty()
@IsAlpha()
lastName!: string;
@IsBoolean()
isEmailVerified!: boolean;
}
export class UserDto {
@IsUUID()
id!: string;
@IsNotEmpty()
@IsString()
@MinLength(3)
username!: string;
@IsEmail()
email!: string;
secret?: never;
@IsNotEmpty()
@IsAlpha()
firstName!: string;
@IsNotEmpty()
@IsAlpha()
lastName!: string;
@IsBoolean()
isEmailVerified!: boolean;
}
export class SignUpUserDto {
id?: never;
@IsNotEmpty()
@IsString()
@MinLength(3)
username!: string;
@IsEmail()
email!: string;
secret?: never;
@IsNotEmpty()
@IsAlpha()
firstName!: string;
@IsNotEmpty()
@IsAlpha()
lastName!: string;
isEmailVerified?: never;
}
export class UpdateUserDto {
id?: never;
@IsOptional()
@IsNotEmpty()
@IsString()
@MinLength(3)
username?: string;
@IsOptional()
@IsEmail()
email?: string;
secret?: never;
@IsOptional()
@IsNotEmpty()
@IsAlpha()
firstName?: string;
@IsOptional()
@IsNotEmpty()
@IsAlpha()
lastName?: string;
isEmailVerified?: never;
}
export class SignInUserDto {
@IsString()
@IsNotEmpty()
username!: string;
@IsNotEmpty()
@IsString()
password!: string;
}