Преглед на файлове

refactor input validation into a mixin

Falko Schindler преди 1 година
родител
ревизия
9042cc0570
променени са 3 файла, в които са добавени 34 реда и са изтрити 35 реда
  1. 4 22
      nicegui/elements/input.py
  2. 27 0
      nicegui/elements/mixins/validation_element.py
  3. 3 13
      nicegui/elements/number.py

+ 4 - 22
nicegui/elements/input.py

@@ -2,10 +2,10 @@ from typing import Any, Callable, Dict, List, Optional
 
 from .icon import Icon
 from .mixins.disableable_element import DisableableElement
-from .mixins.value_element import ValueElement
+from .mixins.validation_element import ValidationElement
 
 
-class Input(ValueElement, DisableableElement):
+class Input(ValidationElement, DisableableElement):
     LOOPBACK = False
 
     def __init__(self,
@@ -16,7 +16,7 @@ class Input(ValueElement, DisableableElement):
                  password_toggle_button: bool = False,
                  on_change: Optional[Callable[..., Any]] = None,
                  autocomplete: Optional[List[str]] = None,
-                 validation: Optional[Dict[str, Callable[[Any], bool]]] = None) -> None:
+                 validation: Dict[str, Callable[..., bool]] = {}) -> None:
         """Text Input
 
         This element is based on Quasar's `QInput <https://quasar.dev/vue-components/input>`_ component.
@@ -37,7 +37,7 @@ class Input(ValueElement, DisableableElement):
         :param autocomplete: optional list of strings for autocompletion
         :param validation: dictionary of validation rules, executed in dict order. e.g. ``{'Too long!': lambda value: len(value) < 3}``
         """
-        super().__init__(tag='q-input', value=value, on_value_change=on_change)
+        super().__init__(tag='q-input', value=value, on_value_change=on_change, validation=validation)
         if label is not None:
             self._props['label'] = label
         if placeholder is not None:
@@ -52,9 +52,6 @@ class Input(ValueElement, DisableableElement):
                     self.props(f'type={"text" if is_hidden else "password"}')
                 icon = Icon('visibility_off').classes('cursor-pointer').on('click', toggle_type)
 
-        self.validation = validation or {}
-        self._error: Optional[str] = None
-
         if autocomplete:
             def find_autocompletion() -> Optional[str]:
                 if self.value:
@@ -75,18 +72,3 @@ class Input(ValueElement, DisableableElement):
 
             self.on('keyup', autocomplete_input)
             self.on('keydown.tab', complete_input)
-
-    def on_value_change(self, value: Any) -> None:
-        super().on_value_change(value)
-        for message, check in self.validation.items():
-            if not check(value):
-                self._error = message
-                self.props(f'error error-message="{message}"')
-                break
-        else:
-            self.props(remove='error')
-
-    @property
-    def error(self) -> Optional[str]:
-        """The latest error message from the validation functions."""
-        return self._error

+ 27 - 0
nicegui/elements/mixins/validation_element.py

@@ -0,0 +1,27 @@
+from typing import Any, Callable, Dict, Optional
+
+from .value_element import ValueElement
+
+
+class ValidationElement(ValueElement):
+
+    def __init__(self, validation: Dict[str, Callable[..., bool]], **kwargs: Any) -> None:
+        super().__init__(**kwargs)
+        self.validation = validation
+        self._error: Optional[str] = None
+
+    @property
+    def error(self) -> Optional[str]:
+        """The latest error message from the validation functions."""
+        return self._error
+
+    def on_value_change(self, value: Any) -> None:
+        super().on_value_change(value)
+        for message, check in self.validation.items():
+            if not check(value):
+                self._error = message
+                self.props(f'error error-message="{message}"')
+                break
+        else:
+            self._error = None
+            self.props(remove='error')

+ 3 - 13
nicegui/elements/number.py

@@ -1,10 +1,10 @@
 from typing import Any, Callable, Dict, Optional
 
 from .mixins.disableable_element import DisableableElement
-from .mixins.value_element import ValueElement
+from .mixins.validation_element import ValidationElement
 
 
-class Number(ValueElement, DisableableElement):
+class Number(ValidationElement, DisableableElement):
     LOOPBACK = False
 
     def __init__(self,
@@ -40,7 +40,7 @@ class Number(ValueElement, DisableableElement):
         :param validation: dictionary of validation rules, e.g. ``{'Too small!': lambda value: value < 3}``
         """
         self.format = format
-        super().__init__(tag='q-input', value=value, on_value_change=on_change)
+        super().__init__(tag='q-input', value=value, on_value_change=on_change, validation=validation)
         self._props['type'] = 'number'
         if label is not None:
             self._props['label'] = label
@@ -56,7 +56,6 @@ class Number(ValueElement, DisableableElement):
             self._props['prefix'] = prefix
         if suffix is not None:
             self._props['suffix'] = suffix
-        self.validation = validation
         self.on('blur', self.sanitize)
 
     def sanitize(self) -> None:
@@ -65,15 +64,6 @@ class Number(ValueElement, DisableableElement):
         value = min(value, self._props.get('max', float('inf')))
         self.set_value(float(self.format % value) if self.format else value)
 
-    def on_value_change(self, value: Any) -> None:
-        super().on_value_change(value)
-        for message, check in self.validation.items():
-            if not check(value):
-                self.props(f'error error-message="{message}"')
-                break
-        else:
-            self.props(remove='error')
-
     def _msg_to_value(self, msg: Dict) -> Any:
         return float(msg['args']) if msg['args'] else None