diff --git a/src/masonite/utils/structures.py b/src/masonite/utils/structures.py index 011a5a22..a52a898c 100644 --- a/src/masonite/utils/structures.py +++ b/src/masonite/utils/structures.py @@ -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 diff --git a/src/masonite/validation/Validator.py b/src/masonite/validation/Validator.py index c3de2284..c7175425 100644 --- a/src/masonite/validation/Validator.py +++ b/src/masonite/validation/Validator.py @@ -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 @@ -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): @@ -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()' diff --git a/tests/features/validation/test_validation.py b/tests/features/validation/test_validation.py index 7737bab0..72573472 100644 --- a/tests/features/validation/test_validation.py +++ b/tests/features/validation/test_validation.py @@ -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."] )