43 lines
2.1 KiB
Python
43 lines
2.1 KiB
Python
import re
|
|
from typing import Optional
|
|
from dataclasses import dataclass, field
|
|
from .Attribute import Attribute
|
|
|
|
@dataclass
|
|
class textAttribute(Attribute):
|
|
"""Class for text attributes."""
|
|
regex: Optional[str] = None
|
|
min_length: Optional[int] = None
|
|
max_length: Optional[int] = 50
|
|
allowed_chars: Optional[str] = None
|
|
|
|
def __post_init__(self):
|
|
"""Post-initialization to set the HTML input type."""
|
|
self.html_input_type = "text"
|
|
|
|
def validate(self) -> Optional[str]:
|
|
"""Validate text-specific attributes."""
|
|
error = super().validate()
|
|
if error:
|
|
return error
|
|
if self.min_length is not None and self.max_length is not None:
|
|
if not isinstance(self.min_length, int) or not isinstance(self.max_length, int):
|
|
return f"Min and max lengths must be integers for '{self.attrib_name}'."
|
|
if int(self.min_length) > int(self.max_length):
|
|
return f"Max length must be greater than min length for '{self.attrib_name}'."
|
|
if self.default_val is not None:
|
|
if self.regex is not None:
|
|
compiled_regex = re.compile(self.regex)
|
|
if not compiled_regex.match(str(self.default_val)):
|
|
return f"Default value for '{self.attrib_name}' must match the pattern: {self.regex}"
|
|
if self.allowed_chars is not None:
|
|
for char in self.default_val:
|
|
if char not in self.allowed_chars:
|
|
return f"Invalid character '{char}' in default value for '{self.attrib_name}'. Allowed characters are: {self.allowed_chars}"
|
|
if self.min_length is not None:
|
|
if len(self.default_val) < int(self.min_length):
|
|
return f"Invalid default value for '{self.attrib_name}'. The minimum length is: {self.min_length}"
|
|
if self.max_length is not None:
|
|
if len(self.default_val) > int(self.max_length):
|
|
return f"Invalid default value for '{self.attrib_name}'. The maximum length is: {self.max_length}"
|
|
return None |