From 3e8272530d933d68aef64e3d8a9036aa0613f17c Mon Sep 17 00:00:00 2001 From: Mohd Hafizuddin M Marzuki Date: Sun, 14 Jul 2024 12:12:57 +0800 Subject: [PATCH] Add ability to get skipped attributes --- src/Validator.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Validator.js b/src/Validator.js index 7ed296d..51b05f1 100644 --- a/src/Validator.js +++ b/src/Validator.js @@ -57,6 +57,7 @@ export default class Validator { #checkers; #replacers; #errors; + #skippedAttributes = []; #implicitAttributes = {}; #stopOnFirstFailure = false; @@ -241,11 +242,13 @@ export default class Validator { this.#errors = new ErrorBag(); const tasks = []; + const skippedAttributes = []; for (const [attribute, rules] of Object.entries(this.#rules)) { let value = this.getValue(attribute); if (Object.hasOwn(rules, 'sometimes') && typeof value === 'undefined') { + skippedAttributes.push(attribute); continue; } @@ -255,14 +258,12 @@ export default class Validator { let noError = true; for (const [rule, parameters] of Object.entries(rules)) { - if (rule === '') { - continue; - } - if ( - !Validator.#implicitRules.includes(rule) && - (typeof value === 'undefined' || (typeof value === 'string' && value.trim() === '') || (isNullable && value === null)) + rule === '' || + (!Validator.#implicitRules.includes(rule) && + (typeof value === 'undefined' || (typeof value === 'string' && value.trim() === '') || (isNullable && value === null))) ) { + skippedAttributes.push(attribute); continue; } @@ -310,6 +311,8 @@ export default class Validator { this.#errors.sortByKeys(Object.keys(this.#rules)); } + this.#skippedAttributes = skippedAttributes.filter((value, index, array) => array.indexOf(value) === index); + return this.#errors; } @@ -483,4 +486,8 @@ export default class Validator { errors() { return this.#errors; } + + skippedAttributes() { + return this.#skippedAttributes; + } }