From: Stephan Müller Date: Tue, 12 Jun 2018 10:16:50 +0000 (+0200) Subject: mgr/dashboard: Add validateIf validator X-Git-Tag: v14.0.1~1120^2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=refs%2Fpull%2F22526%2Fhead;p=ceph.git mgr/dashboard: Add validateIf validator Validate form control if condition is true with given validators Signed-off-by: Stephan Müller --- diff --git a/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.spec.ts b/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.spec.ts index e2e1895f761..fb682970c80 100644 --- a/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.spec.ts +++ b/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.spec.ts @@ -126,4 +126,46 @@ describe('CdValidators', () => { expect(y.valid).toBeTruthy(); }); }); + + describe('validate if condition', () => { + let form: FormGroup; + + beforeEach(() => { + form = new FormGroup({ + x: new FormControl(3), + y: new FormControl(5) + }); + CdValidators.validateIf(form.get('x'), () => ((form && form.get('y').value) || 0) > 10, [ + CdValidators.custom('min', (x) => x < 7), + CdValidators.custom('max', (x) => x > 12) + ]); + }); + + it('should test min error', () => { + const x = form.get('x'); + const y = form.get('y'); + expect(x.valid).toBeTruthy(); + y.setValue(11); + x.updateValueAndValidity(); + expect(x.hasError('min')).toBeTruthy(); + }); + + it('should test max error', () => { + const x = form.get('x'); + const y = form.get('y'); + expect(x.valid).toBeTruthy(); + y.setValue(11); + x.setValue(13); + expect(x.hasError('max')).toBeTruthy(); + }); + + it('should test valid number with validation', () => { + const x = form.get('x'); + const y = form.get('y'); + expect(x.valid).toBeTruthy(); + y.setValue(11); + x.setValue(12); + expect(x.valid).toBeTruthy(); + }); + }); }); diff --git a/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.ts b/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.ts index b8fc514757d..875e18379e9 100644 --- a/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.ts +++ b/src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.ts @@ -73,4 +73,27 @@ export class CdValidators { return null; }; } + + /** + * Validate form control if condition is true with validators. + * + * @param {AbstractControl} formControl + * @param {Function} condition + * @param {ValidatorFn[]} validators + */ + static validateIf( + formControl: AbstractControl, + condition: Function, + validators: ValidatorFn[] + ) { + formControl.setValidators((control: AbstractControl): { + [key: string]: any; + } => { + const value = condition.call(this); + if (value) { + return Validators.compose(validators)(control); + } + return null; + }); + } }