瀏覽代碼

feat: allow regex pattern matchin for any field

Nicolas Meienberger 2 年之前
父節點
當前提交
f35bdb7611

+ 30 - 0
src/client/modules/Apps/utils/validators/validators.test.tsx

@@ -262,4 +262,34 @@ describe('Test: validateAppConfig', () => {
     const result = validateAppConfig(values, fields);
     expect(result).toEqual({});
   });
+
+  it('should validate field against the provided regex', () => {
+    // arrange
+    const valuesCorrect = {
+      version: '1.20.0',
+    };
+
+    const valuesIncorrect = {
+      version: 'abs',
+    };
+
+    const fields: FormField[] = [
+      {
+        label: 'Version',
+        type: 'text',
+        required: true,
+        regex: '^[0-9]+.[0-9]+.[0-9]+$', // only numbers and dots
+        pattern_error: 'Version must be in the format x.y.z',
+        env_variable: 'version',
+      },
+    ];
+
+    // act
+    const resultCorrect = validateAppConfig(valuesCorrect, fields);
+    const resultIncorrect = validateAppConfig(valuesIncorrect, fields);
+
+    // assert
+    expect(resultCorrect).toEqual({});
+    expect(resultIncorrect).toEqual({ version: 'Version must be in the format x.y.z' });
+  });
 });

+ 4 - 0
src/client/modules/Apps/utils/validators/validators.ts

@@ -10,6 +10,10 @@ export const validateField = (field: FormField, value: string | undefined | bool
     return undefined;
   }
 
+  if (field.regex && !validator.matches(value, field.regex)) {
+    return field.pattern_error || `${field.label} must match the pattern ${field.regex}`;
+  }
+
   switch (field.type) {
     case 'text':
       if (field.max && value.length > field.max) {