Skip to content

Commit

Permalink
Added key_missing function to include support for nested validation n…
Browse files Browse the repository at this point in the history
…otation
  • Loading branch information
josephmancuso committed Oct 17, 2024
1 parent 3c3c73f commit f628b13
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/masonite/utils/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,26 @@ def data_get(dictionary, key, default=None):
dotty_key = key.replace("*", ":")
return data(dictionary).get(dotty_key, default)

def missing_key(dictionary, key):
"""Find the first missing element in the dictionary using nested notation.
Arguments:
dictionary {dict} -- a dictionary structure
key {str} -- the dotted (or not) key to look for
Returns:
missing_key {str} -- The first missing key in the nested structure
"""
keys = key.split(".")
current_dict = dictionary

for index, k in enumerate(keys):
if k not in current_dict:
return index - 1
current_dict = current_dict[k]

return None


def data_set(dictionary, key, value, overwrite=True):
"""Set dictionary value at key using nested notation. Values are overridden by default but
Expand Down
6 changes: 4 additions & 2 deletions src/masonite/validation/Validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from .RuleEnclosure import RuleEnclosure
from .MessageBag import MessageBag
from ..utils.structures import data_get
from ..utils.structures import data_get, missing_key
from ..configuration import config
from ..facades import Loader

Expand Down Expand Up @@ -98,6 +98,8 @@ def passes(self, attribute, key, dictionary):
Returns:
bool
"""
self.dictionary = dictionary
self.key = key
return self.find(key, dictionary) and attribute

def message(self, key):
Expand All @@ -109,7 +111,7 @@ def message(self, key):
Returns:
string
"""
return "The {} field is required.".format(key)
return "The {} field is required.".format(key.replace("*", str(missing_key(self.dictionary, self.key))))

def negated_message(self, key):
"""A message to show when this rule is negated using a negation rule like 'isnt()'
Expand Down
2 changes: 1 addition & 1 deletion tests/features/validation/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1908,5 +1908,5 @@ def test_required_with_nested_validation(self):
)
self.assertEqual(len(validate), 1)
self.assertEqual(
validate.all()["key.*.foo"], ["The key.*.foo field is required."]
validate.all()["key.*.foo"], ["The key.0.foo field is required."]
)

0 comments on commit f628b13

Please sign in to comment.