Skip to content

Commit

Permalink
Don't validate if the field shouldn't be shown
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffersonBledsoe committed Mar 12, 2024
1 parent b35cb89 commit caebd31
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,30 @@
validation_message_matcher = re.compile("Validation failed\(([^\)]+)\): ")


def always():
return True


def value_is(value, target_value):
if isinstance(target_value, list):
return value in target_value
return value == target_value


def value_is_not(value, target_value):
if isinstance(target_value, list):
return value not in target_value
return value != target_value


show_when_validators = {
"": always,
"always": always,
"value_is": value_is,
"value_is_not": value_is_not,
}


class Field:
def __init__(self, field_data):
def _attribute(attribute_name: str):
Expand Down Expand Up @@ -37,6 +61,15 @@ def value(self):
def value(self, value):
self._value = value

def should_show(self, show_when_is, target_value):
always_show_validator = show_when_validators['always']
if not show_when_is:
return always_show_validator()
show_when_validator = show_when_validators[show_when_is]
if not show_when_validator:
return always_show_validator
return show_when_validator(value=self.value, target_value=target_value)

@property
def label(self):
return self._label if self._label else self.field_id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,21 @@ def reply(self):

errors = {}
for field in self.fields:
field_errors = field.validate()
show_when = field.show_when_when
should_show = True
if show_when and show_when != "always":
target_field = [
val for val in self.fields if val.id == field.show_when_when
][0]
should_show = (
target_field.should_show(
show_when_is=field.show_when_is, target_value=field.show_when_to
)
if target_field
else True
)
if should_show:
field_errors = field.validate()

if field_errors:
errors[field.field_id] = field_errors
Expand Down

0 comments on commit caebd31

Please sign in to comment.