Below is the create-user-dto file where I have used to create the creation of an account including a username, password and a role. Done using arrays. Although I have set it up still it shows’ white space in my array.
import { Transform } from "class-transformer";
import { IsString, MinLength, MaxLength, Matches, IsIn } from "class-validator";
export class CreateUserDto{
@IsString()
@MinLength(4)
@MaxLength(20)
@Transform(({ value }) => value.trim())
username: string;
@IsString()
@MinLength(8)
@MaxLength(20,{
message: 'Password can contain only 20 characters',
})
@Matches(/(?:(?=.*d)(?=.*[a-z])(?=.*[A-Z]).*)/, {
message: 'Password too weak',
})
@Transform(({ value }) => value.trim())
password: string;
@IsString()
@IsIn(['Teacher', 'Admin'], {
message: 'Role must be either Teacher or Admin'
})
@Transform(({ value }) => value.trim())
role: 'Teacher' | 'Admin';
}
Controller class code: –
@Post('register')
@UsePipes(new ValidationPipe({transform:true, whitelist: true}))
async createUser(@Body() createUserDto: CreateUserDto): Promise<string> {
const existingUser = this.userService.findUser(createUserDto.username);
if(existingUser){
throw new BadRequestException("Username already exists");
}
this.userService.createUser(createUserDto.username, createUserDto.password, createUserDto.role);
return 'User created successfully';
}
Once I save the password with spaces it should save without the spaces right. Still the array has saved the password with an empty space.
New contributor
Salman Rizwan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.