Skip to content

Commit

Permalink
chore: use formFieldInstanceRegistry for validation
Browse files Browse the repository at this point in the history
Related to #1142
  • Loading branch information
Skaiir committed Apr 10, 2024
1 parent 024ae21 commit 247135f
Showing 1 changed file with 14 additions and 40 deletions.
54 changes: 14 additions & 40 deletions packages/form-js-viewer/src/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,64 +204,38 @@ export class Form {
* @returns {Errors}
*/
validate() {
const formFields = this.get('formFields'),
formFieldRegistry = this.get('formFieldRegistry'),
pathRegistry = this.get('pathRegistry'),
const formFieldRegistry = this.get('formFieldRegistry'),
formFieldInstanceRegistry = this.get('formFieldInstanceRegistry'),
validator = this.get('validator');

const { data } = this._getState();
const errors = {};

const getErrorPath = (field, indexes) => [ field.id, ...Object.values(indexes || {}) ];
const getErrorPath = (id, indexes) => [ id, ...Object.values(indexes || {}) ];

function validateFieldRecursively(errors, field, indexes) {
const { disabled, type, isRepeating } = field;
const { config: fieldConfig } = formFields.get(type);
formFieldInstanceRegistry.getAllKeyed().forEach(({ id, valuePath, indexes }) => {

const field = formFieldRegistry.get(id);

// (1) Skip disabled fields
if (disabled) {
if (field.disabled) {
return;
}

// (2) Validate the field
const valuePath = pathRegistry.getValuePath(field, { indexes });
const valueData = get(data, valuePath);
const fieldErrors = validator.validateField(field, valueData);
const value = get(data, valuePath);
const fieldErrors = validator.validateField(field, value);

if (fieldErrors.length) {
set(errors, getErrorPath(field, indexes), fieldErrors);
}

// (3) Process parents
if (!Array.isArray(field.components)) {
return;
}

// (4a) Recurse repeatable parents both across the indexes of repetition and the children
if (fieldConfig.repeatable && isRepeating) {

if (!Array.isArray(valueData)) {
return;
}

valueData.forEach((_, index) => {
field.components.forEach((component) => {
validateFieldRecursively(errors, component, { ...indexes, [field.id]: index });
});
});

return;
}

// (4b) Recurse non-repeatable parents only across the children
field.components.forEach((component) => validateFieldRecursively(errors, component, indexes));
}
});

const workingErrors = {};
validateFieldRecursively(workingErrors, formFieldRegistry.getForm());
const filteredErrors = this._applyConditions(workingErrors, data, { getFilterPath: getErrorPath, leafNodeDeletionOnly: true });
this._setState({ errors: filteredErrors });
this._setState({ errors });

return filteredErrors;
// @ts-ignore
return errors;
}

/**
Expand Down

0 comments on commit 247135f

Please sign in to comment.