imp|

Using the directives of FormBus without the submission functionality

FormBus does two things. It submits the form data (request) and displays/toggles success, error messages/classes related to the submission (response).

And while it's true that these are two separate concerns, and the two functionalities could be separated, I'm happy that it does both. Because that's the promise of the library, you write a valid HTML, and you are mostly done.

But what if you only want to use FormBus's validation logic and the directives without the submission part? Is that possible? The answer is: yes.

To achieve this, we have to import some of the internal building blocks of the library:

import defaultConfig from 'formbus/src/core/default-config';
import directivesHandlerMap from 'formbus/src/core/directives-handler-map';

Then we have to loop over the registered directives and pass the data they expect:

for (const directive in directivesHandlerMap) {
directivesHandlerMap[directive](
responseData,
sectionEl,
strategy,
defaultConfig
);
}

And surprisingly, that's it.

Here's how I put all this together for a project:

import defaultConfig from 'formbus/src/core/default-config';
import directivesHandlerMap from 'formbus/src/core/directives-handler-map';

const orderResponseStrategy = {...};

const orderFormValidator = (orderSectionEl) => {
const validate = (responseData) => {
for (const directive in directivesHandlerMap) {
directivesHandlerMap[directive](
responseData,
orderSectionEl,
orderResponseStrategy,
defaultConfig
);
}
};

return {
validate
};
};

export default orderFormValidator;

Then I imported this module into the existing codebase:

import orderFormValidator from './orderFormValidator';

const orderSectionEl = document.querySelector('.order');

const postOrderData = (data) => {
p5.httpPost(
'/order',
'json',
data,
(response) => {
const validator = orderFormValidator(orderSectionEl);

validator.validate();
},
(response) => {
console.log(response);
}
);
};

I'm thinking of providing a public-facing validate method to do this without the need to import internal modules. That might be a good idea.

Back to all posts

implenton is my (Mészáros Róbert) online web development-related presence, playground, and the name of my company of one.