Repository: markusressel/container-app-conf

Issue:
Restrict valid input of StringConfigEntry using regex
As the title states.

Discussion:

Patch:
diff --git a/container_app_conf/entry/string.py b/container_app_conf/entry/string.py
index ce12615..e2d2a6a 100644
--- a/container_app_conf/entry/string.py
+++ b/container_app_conf/entry/string.py
@@ -17,6 +17,7 @@
 #  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 #  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 #  SOFTWARE.
+import re
 
 from container_app_conf import ConfigEntry
 
@@ -24,6 +25,11 @@ from container_app_conf import ConfigEntry
 class StringConfigEntry(ConfigEntry):
     _example = "text"
 
+    def __init__(self, key_path: [str], example: any = None, description: str or None = None, default: any = None,
+                 none_allowed: bool = None, regex: str = None):
+        self.regex = re.compile(regex) if regex is not None else None
+        super().__init__(key_path, example, description, default, none_allowed)
+
     def _value_to_type(self, value: any) -> str or None:
         """
         Converts the given type to the expected type
@@ -35,4 +41,8 @@ class StringConfigEntry(ConfigEntry):
             if s.lower() in ['none', 'null', 'nil']:
                 return None
 
+        if self.regex is not None:
+            if not self.regex.match(s):
+                self._raise_invalid_value(s)
+
         return s


Test patch:
diff --git a/tests/entry_test.py b/tests/entry_test.py
index 80c6a8c..ab36331 100644
--- a/tests/entry_test.py
+++ b/tests/entry_test.py
@@ -48,6 +48,17 @@ class EntryTest(EntryTestBase):
 
         self.assert_input_output(config_entry, input_output)
 
+    def test_string_entry_regex(self):
+        config_entry = StringConfigEntry(key_path=["string"], none_allowed=True, regex="^[0-9]*$")
+
+        input_output = [
+            ("5", "5"),
+            ("hello", ValueError),
+            ("$stuff=)(&/%$§", ValueError),
+        ]
+
+        self.assert_input_output(config_entry, input_output)
+
     def test_regex_entry(self):
         config_entry = RegexConfigEntry(key_path=["regex"], none_allowed=True)