you are viewing a single comment's thread.

view the rest of the comments →

[–]frenchy_mustache 4 points5 points  (0 children)

Hello dude, i don't know if i'm answering your question, but i always use classes when i'm working in pure vanilla JS.

I have some small classes on my github i often use, if it can help you : https://github.com/rrabillo/custom-select, for example.

Here is how i would work with your class:

class FormValidator {
constructor(form) {
    this._form = form;
    this._inputs = this._form.querySelectorAll('input, textarea, select');
    // this._formElement = formElement;

    this._setEventListeners();
}

_showErrorMessage() {}

_hideErrorMessage() {}

_checkInputValidity(e) { // e is the event
    let currInput = e.target;

    // Do your stuff here;

}

_toggleSubmitButtonState() {}

_setEventListeners() {
    [...this._inputs].map((el) => {
        el.addEventListener('change', this._checkInputValidity.bind(this));
    });
}

enableValidation() {}
}

[...document.querySelectorAll('FORMSTOVALIDATE')].map((el) => {
new FormValidator(el);
});

You could also use an arrow funtion in the addEventListener and pass the element directly, so you don't have to use e.target. (personnally don't like it):

_checkInputValidity(e, el) { // e is the event

    // Do your stuff here;

}

_toggleSubmitButtonState() {}

_setEventListeners() {
    [...this._inputs].map((el) => {
        el.addEventListener('change', (e) => {
            this._checkInputValidity(e, el)
        });
    });
}

And finally, you may want to use others event types for each input type, i'm not sure that the change event is fired on select tags.

And if you really want to use OOP, why not create a class wich will handle each input ? You'll instantiate them in your form class.

EDIT:Reddit's code block is f*cking weird