0

i am trying to build a Form Validator. when i am trying to access the rules object, i am getting a Uncaught ReferenceError. What am i doing wrong here?

class Validator {
    constructor(formID, rules) {
        this.form = document.querySelector(formID);
        this.rules = rules;
        this.init();
    }

    init() {
        form.addEventListener('submit', this.validate);
    }

    validate(e) {
        e.preventDefault();
        let formElements = form.elements;
        let toCheck = [];
        for (let elem of formElements) {
            if(elem.type != 'submit') {
                toCheck.push(elem);
            }
        }
        toCheck.forEach(function(elem) {
            let element = elem.type;
            console.log(rules["name"]); //Uncaught ReferenceError: rules is not defined
        });
    }
}

const val = new Validator('#form', { name: "checked by namechecker", email: "checked by mail checker"});

EDIT: Sorry, i am not seeing the dublicate, as for a example i could console.log(form) in the same spot without an error.

EDIT 2: After some help in the comments i do understand that it is a duplicate. Sorry.

  • 1
    `form.addEventListener('submit', this.validate.bind(this));` – Emissary May 23 '17 at 12:06
  • 1
    `rules` is not defined. It should be `(elem) => {` and `this.rules`, in addition to this ^^^ . – Estus Flask May 23 '17 at 12:14
  • Thats not working either. What confuses me is that i could console.log(form) everywhere in the code. But not "rules"nowhere –  May 23 '17 at 12:19
  • 1
    It should. If it's not, you're missing something more than a single property. You can't access class properties with just `form` and `rules`. From the code above, `console.log(form)` can't work. You probably have `form` global or something. – Estus Flask May 23 '17 at 12:23
  • @estus ok. now it is working. What led me on the wrong track was the globally available `form`. Thanks for helping estus and Emmissary –  May 23 '17 at 12:32

0 Answers0