If an empty string is specified for email, both @IsNotEmpty and @IsEmail validation will fail.
\nTwo messages are generated.
I want to skip IsEmail validation in these cases, since it is sufficient to just tell the user that it is empty.
I know that this can be achieved by creating a Custom validation decorator that performs the same checks as IsEmail only if it is non-empty.
If there is another, simpler solution, I would like to know.
\nThanks.
","upvoteCount":1,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"@onozaty use the stopAtFirstError option when calling validate(). this stops validation on each property after the first constraint fails, so if @IsNotEmpty already caught the empty string, @IsEmail won't run:
const errors = await validate(dto, { stopAtFirstError: true });in NestJS, pass it to ValidationPipe:
app.useGlobalPipes(new ValidationPipe({ stopAtFirstError: true }));this is a built-in option in class-validator v0.14+. make sure your decorators are ordered the way you want (first decorator = first check).
\nref: class-validator validate options
","upvoteCount":2,"url":"https://github.com/typestack/class-validator/discussions/2419#discussioncomment-15764057"}}}-
import { IsEmail, IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty()
@IsEmail()
email: string;
}If an empty string is specified for email, both
I want to skip I know that this can be achieved by creating a Custom validation decorator that performs the same checks as If there is another, simpler solution, I would like to know. Thanks. |
Beta Was this translation helpful? Give feedback.
-
|
@onozaty use the const errors = await validate(dto, { stopAtFirstError: true });in NestJS, pass it to app.useGlobalPipes(new ValidationPipe({ stopAtFirstError: true }));this is a built-in option in class-validator v0.14+. make sure your decorators are ordered the way you want (first decorator = first check). |
Beta Was this translation helpful? Give feedback.
@onozaty use the
stopAtFirstErroroption when callingvalidate(). this stops validation on each property after the first constraint fails, so if@IsNotEmptyalready caught the empty string,@IsEmailwon't run:in NestJS, pass it to
ValidationPipe:this is a built-in option in class-validator v0.14+. make sure your decorators are ordered the way you want (first decorator = first check).
ref: class-validator validate options