diff --git a/Client/src/Validation/error.js b/Client/src/Validation/error.js index 0d1359ad5..017fa9a46 100644 --- a/Client/src/Validation/error.js +++ b/Client/src/Validation/error.js @@ -8,6 +8,31 @@ const buildErrors = (prev, id, error) => { return updatedErrors; }; +/** + * Processes Joi validation errors and returns a filtered object of error messages for fields that have been touched. + * + * @param {Object} validation - The Joi validation result object. + * @param {Object} validation.error - The error property of the validation result containing details of validation failures. + * @param {Object[]} validation.error.details - An array of error details from the Joi validation. Each item contains information about the path and the message. + * @param {Object} touchedErrors - An object representing which fields have been interacted with. Keys are field IDs (field names), and values are booleans indicating whether the field has been touched. + * @returns {Object} - An object where keys are the field IDs (if they exist in `touchedErrors` and are in the error details) and values are their corresponding error messages. + */ +const getTouchedFieldErrors = (validation, touchedErrors) => { + let newErrors = {}; + + if (validation?.error) { + newErrors = validation.error.details.reduce((errors, detail) => { + const fieldId = detail.path[0]; + if (touchedErrors[fieldId] && !(fieldId in errors)) { + errors[fieldId] = detail.message; + } + return errors; + }, {}); + } + + return newErrors; +}; + const hasValidationErrors = (form, validation, setErrors) => { const { error } = validation.validate(form, { abortEarly: false, @@ -53,4 +78,4 @@ const hasValidationErrors = (form, validation, setErrors) => { } return false; }; -export { buildErrors, hasValidationErrors }; +export { buildErrors, hasValidationErrors, getTouchedFieldErrors };