From f71b2d8fe261530abaeab8da5a1d68d2845392c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kuffel?= Date: Mon, 27 Dec 2021 10:41:05 +0100 Subject: [PATCH] fix: allow numbers and booleans as validation message "$value" tokens --- src/validation/ValidationUtils.ts | 2 +- test/functional/validation-options.spec.ts | 36 +++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/validation/ValidationUtils.ts b/src/validation/ValidationUtils.ts index 6de3f21724..26a8c18d27 100644 --- a/src/validation/ValidationUtils.ts +++ b/src/validation/ValidationUtils.ts @@ -36,7 +36,7 @@ export class ValidationUtils { messageString && validationArguments.value !== undefined && validationArguments.value !== null && - typeof validationArguments.value === 'string' + ['string', 'boolean', 'number'].includes(typeof validationArguments.value) ) messageString = messageString.replace(/\$value/g, validationArguments.value); if (messageString) messageString = messageString.replace(/\$property/g, validationArguments.property); diff --git a/test/functional/validation-options.spec.ts b/test/functional/validation-options.spec.ts index 9e57669fb1..3d3855ee85 100644 --- a/test/functional/validation-options.spec.ts +++ b/test/functional/validation-options.spec.ts @@ -1,7 +1,9 @@ import { Contains, + Equals, IsDefined, Matches, + Max, MinLength, Validate, ValidateNested, @@ -56,7 +58,7 @@ describe('message', () => { }); }); - it('$value token should be replaced in a custom message', () => { + it('$value token should be replaced in a custom message with a string', () => { class MyClass { @MinLength(2, { message: args => { @@ -76,6 +78,38 @@ describe('message', () => { }); }); + it('$value token should be replaced in a custom message with a number', () => { + class MyClass { + @Max(100, { message: 'Maximum value is $constraint1, but actual is $value' }) + val: number = 50; + } + + const model = new MyClass(); + model.val = 101; + return validator.validate(model).then(errors => { + expect(errors.length).toEqual(1); + expect(errors[0].constraints).toEqual({ + max: 'Maximum value is 100, but actual is 101', + }); + }); + }); + + it('$value token should be replaced in a custom message with a boolean', () => { + class MyClass { + @Equals(true, { message: 'Value must be $constraint1, but actual is $value' }) + val: boolean = false; + } + + const model = new MyClass(); + model.val = false; + return validator.validate(model).then(errors => { + expect(errors.length).toEqual(1); + expect(errors[0].constraints).toEqual({ + equals: 'Value must be true, but actual is false', + }); + }); + }); + it('$constraint1 token should be replaced in a custom message', () => { class MyClass { @Contains('hello', {