class-validator
class-validator copied to clipboard
feat: Support for external message composing
Created a new Validator option field, externalMessageComposer, to support returning the supplied validation parameters inside the decorator back as an error message to allow users to create their standard custom messages, and allow them to easily create localized error messages. It is no longer the only option to write custom error messages every time using a decorator which breaks the DRY principle; the new feature helps clean code for custom error messages.
Description
Sample Code:
export class DtoTest {
@MinLength(30)
title: string;
}
const dto = new DtoTest();
dto.title = "Length of this messsage is 29";
const options = {
externalMessageComposer: false,
};
validate(dto, options).then((errors: string | any[]) => {
// errors is an array of validation errors
if (errors.length > 0) {
console.log("validation failed. errors: ", errors);
} else {
console.log("validation succeed");
}
});
Before the feature support: Resulting Error Message inside ValidationError is:
constraints: {
minLength: 'title must be longer than or equal to 30 characters'
}
Now if we set externalMessageComposer to true:
const options = {
externalMessageComposer: true,
};
After the feature support and the externalMessageComposer is set to true: Resulting Error Message inside ValidationError is now:
constraints: { minLength: '30' }
By this way; we can compose our message, as it was previosly not possible to get the validation parameter ('30').
For example; user may compose the following error message as the {1} argument ('30' in this example) is supplied within the class-validator error message.
"minLength": "{0} must be longer than or equal to {1} characters",
Checklist
- [x] the pull request title describes what this PR does (not a vague title like
Update index.md
) - [x] the pull request targets the default branch of the repository (
develop
) - [x] the code follows the established code style of the repository
-
npm run prettier:check
passes -
npm run lint:check
passes
-
- [ ] tests are added for the changes I made (if any source code was modified)
- [ ] documentation added or updated
- [x] I have run the project locally and verified that there are no errors
Fixes
fixes #[issue number], fixes #[issue number]