From fa3b70c06b5e2f604ecb45a0ace83e9894bbff46 Mon Sep 17 00:00:00 2001 From: Ricardo Marques Date: Mon, 18 Jun 2018 12:42:08 +0100 Subject: [PATCH] mgr/dashboard: Add match validator Signed-off-by: Ricardo Marques --- .../app/shared/forms/cd-validators.spec.ts | 31 +++++++++++++++++++ .../src/app/shared/forms/cd-validators.ts | 16 ++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.spec.ts b/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.spec.ts index fb682970c8070..3f111b555e7c4 100644 --- a/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.spec.ts +++ b/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.spec.ts @@ -168,4 +168,35 @@ describe('CdValidators', () => { expect(x.valid).toBeTruthy(); }); }); + + describe('match', () => { + let form: FormGroup; + + beforeEach(() => { + form = new FormGroup({ + x: new FormControl(), + y: new FormControl() + }); + }); + + it('should error when values are different', () => { + const x = form.get('x'); + const y = form.get('y'); + x.setValue('aaa'); + y.setValue('aab'); + CdValidators.match('x', 'y')(form); + expect(x.hasError('match')).toBeFalsy(); + expect(y.hasError('match')).toBeTruthy(); + }); + + it('should not error when values are equal', () => { + const x = form.get('x'); + const y = form.get('y'); + x.setValue('aaa'); + y.setValue('aaa'); + CdValidators.match('x', 'y')(form); + expect(x.hasError('match')).toBeFalsy(); + expect(y.hasError('match')).toBeFalsy(); + }); + }); }); diff --git a/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.ts b/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.ts index 875e18379e945..37b933457ab15 100644 --- a/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.ts +++ b/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.ts @@ -96,4 +96,20 @@ export class CdValidators { return null; }); } + + /** + * Validate if control1 and control2 have the same value. + * Error will be added to control2. + * + * @param {string} control1 + * @param {string} control2 + */ + static match(control1: string, control2: string): ValidatorFn { + return (control: AbstractControl): { [key: string]: any } => { + if (control.get(control1).value !== control.get(control2).value) { + control.get(control2).setErrors({ ['match']: true }); + } + return null; + }; + } } -- 2.39.5