class-validator: feat: add option to stop validation after first validation error

If i apply the following annotations:

  @IsNotEmpty()
  @IsInt()
  @Min(0)
  foobar: number;

The validation result will be:

{ 
  "value": null, 
  "property": "foobar", 
  "children": [], 
  "constraints": {
    "min": "foobar must be greater than 0",
   "isInt": "foobar must be an integer number", 
   "isNotEmpty": "foobar should not be empty" 
  } 
}

If no value is given (i.e.: foobar === null), I only want the validation result of @IsNotEmpty. All the others are quite useless… worse: since the validation errors (the constraints) are stored in an object, the ordering is lost so I cannot “just take the first error constraint” 😦

Expected result:

{ 
  "value": null, 
  "property": "foobar", 
  "children": [], 
  "constraints": {
   "isNotEmpty": "foobar should not be empty" 
  } 
}

or:

 { 
  "value": null, 
  "property": "foobar", 
  "children": [], 
  "constraints": [
    {"isNotEmpty": "foobar should not be empty" },
    {"isInt": "foobar must be an integer number"},
    { "min": "foobar must be greater than 0"}
  ]
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 25
  • Comments: 21 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I agree. Would be much efficient when no validators would run after one failed.

My example:

  @IsInt()
  @IsInModel({ model: User, property: 'id' })
  userId: number;

IsInModel will still run even though userId sent as string.

And error will look doubled and not so smart: User id must be an integer number. Invalid user id

It would be nice if there is a setting that makes the validator stop after the very first fail. For example, I have custom constraint that checks the database for email existence. I used the following decorators:

@IsNotEmpty()
@Length(3, 50)
@EmailNotExists()
email: string;

This makes database query even if email is empty or with less than 3 characters. Of course I could add additional checks in my constraint, but it makes no sense to do that.

Yes, this is a feature request 😃

The result with all validations as list would be nice:

{ "value": null,
  "property": "foobar",
  "children": [], 
  "constraints": [ 
    {"isNotEmpty": "foobar should not be empty" },
    {"isInt": "foobar must be an integer number"},
    { "min": "foobar must be greater than 0"}
}

with the constraints ordering same as annotation ordering