Skip to content

Commit

Permalink
fix: allow numbers and booleans as validation message "$value" tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
kffl committed Dec 27, 2021
1 parent d9ab052 commit f71b2d8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/validation/ValidationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
36 changes: 35 additions & 1 deletion test/functional/validation-options.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
Contains,
Equals,
IsDefined,
Matches,
Max,
MinLength,
Validate,
ValidateNested,
Expand Down Expand Up @@ -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 => {
Expand All @@ -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', {
Expand Down

0 comments on commit f71b2d8

Please sign in to comment.