]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
mgr/dashboard: Add validateIf validator 22526/head
authorStephan Müller <smueller@suse.com>
Tue, 12 Jun 2018 10:16:50 +0000 (12:16 +0200)
committerStephan Müller <smueller@suse.com>
Tue, 12 Jun 2018 15:06:17 +0000 (17:06 +0200)
Validate form control if condition is true with given validators

Signed-off-by: Stephan Müller <smueller@suse.com>
src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.spec.ts
src/pybind/mgr/dashboard/frontend/src/app/shared/validators/cd-validators.ts

index e2e1895f76109afd579cdbd6f07de63c6df59531..fb682970c807095f39a9f84af8d7db58311902b5 100644 (file)
@@ -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();
+    });
+  });
 });
index b8fc514757df31de5f33c7ef4473161a9c012cac..875e18379e9456469b737aa4d9495528f49c25a1 100644 (file)
@@ -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;
+    });
+  }
 }