Skip to content

feat: add option to stop validation at first error #620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export interface ValidatorOptions {
};

forbidUnknownValues?: boolean;
stopAtFirstError?: boolean;
}
```

Expand Down
6 changes: 6 additions & 0 deletions src/validation/ValidationExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,12 @@ export class ValidationExecutor {
metadatas.forEach(metadata => {
this.metadataStorage.getTargetValidatorConstraints(metadata.constraintCls).forEach(customConstraintMetadata => {
if (customConstraintMetadata.async && this.ignoreAsyncValidations) return;
if (
this.validatorOptions &&
this.validatorOptions.stopAtFirstError &&
Object.keys(error.constraints || {}).length > 0
)
return;

const validationArguments: ValidationArguments = {
targetName: object.constructor ? (object.constructor as any).name : undefined,
Expand Down
5 changes: 5 additions & 0 deletions src/validation/ValidatorOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,9 @@ export interface ValidatorOptions {
* Settings true will cause fail validation of unknown objects.
*/
forbidUnknownValues?: boolean;

/**
* When set to true, validation of the given property will stop after encountering the first error. Defaults to false.
*/
stopAtFirstError?: boolean;
}
20 changes: 20 additions & 0 deletions test/functional/validation-options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1086,4 +1086,24 @@ describe('context', () => {
expect(errors[1].contexts['contains']).toEqual({ bye: 'now' });
});
});

it('should stop at first error.', () => {
class MyClass {
@IsDefined({
message: 'isDefined',
})
@Contains('hello', {
message: 'String is not valid. You string must contain a hello word',
})
sameProperty: string;
}

const model = new MyClass();
return validator.validate(model, { stopAtFirstError: true }).then(errors => {
console.log();
expect(errors.length).toEqual(1);
expect(Object.keys(errors[0].constraints).length).toBe(1);
expect(errors[0].constraints['isDefined']).toBe('isDefined');
});
});
});