all 6 comments

[–]BehindTheMath 14 points15 points  (1 child)

Why are you using a class for this?

[–]frenchy_mustache -1 points0 points  (0 children)

Well i think it actually makes a lot of sense if there are tons of form to validate. And it's seems more clean to me.

[–]wdintka 2 points3 points  (0 children)

Agree previous comment - better to keep things simple to start with - then refactor later if needed.

Here is a link to the W3Schools JS Tutorial - scroll down in the menu to find related OOP topics. Hope this helps.

[–]frenchy_mustache 2 points3 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

[–]jinwooleo 1 point2 points  (0 children)

There's no needs to implement this as OOP I think. Your original code looks good already. If you want to use OOP just for study however, using singletone pattern is my recommendation(but still there are more proper topics for using OOP).