|
8 | 8 | ValidateNested,
|
9 | 9 | ValidatorConstraint,
|
10 | 10 | IsOptional,
|
11 |
| - IsNotEmpty, |
12 |
| - Allow, |
| 11 | + Min, |
| 12 | + Max, |
13 | 13 | } from '../../src/decorator/decorators';
|
14 | 14 | import { Validator } from '../../src/validation/Validator';
|
15 | 15 | import {
|
@@ -1251,3 +1251,66 @@ describe('context', () => {
|
1251 | 1251 | return Promise.all([hasStopAtFirstError, hasNotStopAtFirstError]);
|
1252 | 1252 | });
|
1253 | 1253 | });
|
| 1254 | + |
| 1255 | + |
| 1256 | +describe('validateIf', () => { |
| 1257 | + class MyClass { |
| 1258 | + @Min(5, { |
| 1259 | + message: 'min', |
| 1260 | + validateIf: (value, args) => { |
| 1261 | + const obj = args.object as MyClass; |
| 1262 | + return !obj.someOtherProperty || obj.someOtherProperty === 'min'; |
| 1263 | + } |
| 1264 | + }) |
| 1265 | + @Max(3, { |
| 1266 | + message: 'max', |
| 1267 | + validateIf: (value, args) => { |
| 1268 | + const obj = args.object as MyClass; |
| 1269 | + return !obj.someOtherProperty || obj.someOtherProperty === 'max'; |
| 1270 | + } |
| 1271 | + }) |
| 1272 | + someProperty: number; |
| 1273 | + |
| 1274 | + someOtherProperty: string; |
| 1275 | + } |
| 1276 | + |
| 1277 | + describe('should validate if validateIf return true.', () => { |
| 1278 | + it('should only validate min', () => { |
| 1279 | + const model = new MyClass(); |
| 1280 | + model.someProperty = 4 |
| 1281 | + model.someOtherProperty = 'min'; |
| 1282 | + return validator.validate(model).then(errors => { |
| 1283 | + expect(errors.length).toEqual(1); |
| 1284 | + expect(errors[0].constraints['min']).toBe('min'); |
| 1285 | + expect(errors[0].constraints['max']).toBe(undefined); |
| 1286 | + }); |
| 1287 | + }) |
| 1288 | + it('should only validate max', () => { |
| 1289 | + const model = new MyClass(); |
| 1290 | + model.someProperty = 4 |
| 1291 | + model.someOtherProperty = 'max'; |
| 1292 | + return validator.validate(model).then(errors => { |
| 1293 | + expect(errors.length).toEqual(1); |
| 1294 | + expect(errors[0].constraints['min']).toBe(undefined); |
| 1295 | + expect(errors[0].constraints['max']).toBe('max'); |
| 1296 | + }); |
| 1297 | + }) |
| 1298 | + it('should validate both', () => { |
| 1299 | + const model = new MyClass(); |
| 1300 | + model.someProperty = 4 |
| 1301 | + return validator.validate(model).then(errors => { |
| 1302 | + expect(errors.length).toEqual(1); |
| 1303 | + expect(errors[0].constraints['min']).toBe('min'); |
| 1304 | + expect(errors[0].constraints['max']).toBe('max'); |
| 1305 | + }); |
| 1306 | + }) |
| 1307 | + it('should validate none', () => { |
| 1308 | + const model = new MyClass(); |
| 1309 | + model.someProperty = 4 |
| 1310 | + model.someOtherProperty = 'other'; |
| 1311 | + return validator.validate(model).then(errors => { |
| 1312 | + expect(errors.length).toEqual(0); |
| 1313 | + }); |
| 1314 | + }) |
| 1315 | + }); |
| 1316 | +}) |
0 commit comments