|
8 | 8 | ValidatorConstraint,
|
9 | 9 | IsOptional,
|
10 | 10 | IsNotEmpty,
|
| 11 | + Min, |
| 12 | + Max, |
11 | 13 | } from '../../src/decorator/decorators';
|
12 | 14 | import { Validator } from '../../src/validation/Validator';
|
13 | 15 | import {
|
@@ -1215,3 +1217,66 @@ describe('context', () => {
|
1215 | 1217 | });
|
1216 | 1218 | });
|
1217 | 1219 | });
|
| 1220 | + |
| 1221 | + |
| 1222 | +describe('validateIf', () => { |
| 1223 | + class MyClass { |
| 1224 | + @Min(5, { |
| 1225 | + message: 'min', |
| 1226 | + validateIf: (value, args) => { |
| 1227 | + const obj = args.object as MyClass; |
| 1228 | + return !obj.someOtherProperty || obj.someOtherProperty === 'min'; |
| 1229 | + } |
| 1230 | + }) |
| 1231 | + @Max(3, { |
| 1232 | + message: 'max', |
| 1233 | + validateIf: (value, args) => { |
| 1234 | + const obj = args.object as MyClass; |
| 1235 | + return !obj.someOtherProperty || obj.someOtherProperty === 'max'; |
| 1236 | + } |
| 1237 | + }) |
| 1238 | + someProperty: number; |
| 1239 | + |
| 1240 | + someOtherProperty: string; |
| 1241 | + } |
| 1242 | + |
| 1243 | + describe('should validate if validateIf return true.', () => { |
| 1244 | + it('should only validate min', () => { |
| 1245 | + const model = new MyClass(); |
| 1246 | + model.someProperty = 4 |
| 1247 | + model.someOtherProperty = 'min'; |
| 1248 | + return validator.validate(model).then(errors => { |
| 1249 | + expect(errors.length).toEqual(1); |
| 1250 | + expect(errors[0].constraints['min']).toBe('min'); |
| 1251 | + expect(errors[0].constraints['max']).toBe(undefined); |
| 1252 | + }); |
| 1253 | + }) |
| 1254 | + it('should only validate max', () => { |
| 1255 | + const model = new MyClass(); |
| 1256 | + model.someProperty = 4 |
| 1257 | + model.someOtherProperty = 'max'; |
| 1258 | + return validator.validate(model).then(errors => { |
| 1259 | + expect(errors.length).toEqual(1); |
| 1260 | + expect(errors[0].constraints['min']).toBe(undefined); |
| 1261 | + expect(errors[0].constraints['max']).toBe('max'); |
| 1262 | + }); |
| 1263 | + }) |
| 1264 | + it('should validate both', () => { |
| 1265 | + const model = new MyClass(); |
| 1266 | + model.someProperty = 4 |
| 1267 | + return validator.validate(model).then(errors => { |
| 1268 | + expect(errors.length).toEqual(1); |
| 1269 | + expect(errors[0].constraints['min']).toBe('min'); |
| 1270 | + expect(errors[0].constraints['max']).toBe('max'); |
| 1271 | + }); |
| 1272 | + }) |
| 1273 | + it('should validate none', () => { |
| 1274 | + const model = new MyClass(); |
| 1275 | + model.someProperty = 4 |
| 1276 | + model.someOtherProperty = 'other'; |
| 1277 | + return validator.validate(model).then(errors => { |
| 1278 | + expect(errors.length).toEqual(0); |
| 1279 | + }); |
| 1280 | + }) |
| 1281 | + }); |
| 1282 | +}) |
0 commit comments