]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
mgr/dashboard: Add custom validator
authorStephan Müller <smueller@suse.com>
Tue, 12 Jun 2018 10:14:59 +0000 (12:14 +0200)
committerStephan Müller <smueller@suse.com>
Tue, 12 Jun 2018 15:03:46 +0000 (17:03 +0200)
Custom validation by passing a name for the error and a function as
error condition.

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 56c6232629020b011324ed47f4857d683b0e4da8..e2e1895f76109afd579cdbd6f07de63c6df59531 100644 (file)
@@ -92,4 +92,38 @@ describe('CdValidators', () => {
       expect(validatorFn(form.controls['y'])).toEqual({ required: true });
     });
   });
+
+  describe('custom validation', () => {
+    let form: FormGroup;
+
+    beforeEach(() => {
+      form = new FormGroup({
+        x: new FormControl(3, CdValidators.custom('odd', (x) => x % 2 === 1)),
+        y: new FormControl(
+          5,
+          CdValidators.custom('not-dividable-by-x', (y) => {
+            const x = (form && form.get('x').value) || 1;
+            return y % x !== 0;
+          })
+        )
+      });
+    });
+
+    it('should test error and valid condition for odd x', () => {
+      const x = form.get('x');
+      x.updateValueAndValidity();
+      expect(x.hasError('odd')).toBeTruthy();
+      x.setValue(4);
+      expect(x.valid).toBeTruthy();
+    });
+
+    it('should test error and valid condition for y if its dividable by x', () => {
+      const y = form.get('y');
+      y.updateValueAndValidity();
+      expect(y.hasError('not-dividable-by-x')).toBeTruthy();
+      y.setValue(6);
+      y.updateValueAndValidity();
+      expect(y.valid).toBeTruthy();
+    });
+  });
 });
index 0c1a9b53ebc91ee43e3333f4b0b3fd0e45177373..b8fc514757df31de5f33c7ef4473161a9c012cac 100644 (file)
@@ -56,4 +56,21 @@ export class CdValidators {
       return success ? { required: true } : null;
     };
   }
+
+  /**
+   * Custom validation by passing a name for the error and a function as error condition.
+   *
+   * @param {string} error
+   * @param {Function} condition - a truthy return value will trigger the error
+   * @returns {ValidatorFn}
+   */
+  static custom(error: string, condition: Function): ValidatorFn {
+    return (control: AbstractControl): { [key: string]: any } => {
+      const value = condition.call(this, control.value);
+      if (value) {
+        return { [error]: value };
+      }
+      return null;
+    };
+  }
 }