'Javascript trying to create my own form validation doesn't work
I have this form which you can create an array with. I don't want the form to be created when there are some specific circumstances. I have this array and in it you can create questions and answers with a form, but I have a few rules. The array can only be created when there are more than 3 question and when every question has at least 3 answers.
My code:
Checker() {
/**
* @type {Question[]}
*/
let questions = NewArray.structure.questions;
for (let i = 0; i < questions.length; i++) {
if (questions[i].answers.length <= 2) {
console.log(questions[i])
alert('Question number ' + i + ' has to few answers')
} else if (questions.length <= 2) {
alert('You need at least 3 questions!');
} else {
return true;
}
}
}
if (NewArray.Checker() === true) {
Do something
} else {
Do nothing
}
Here is questions the array with the questions and questions[i].answers the answers of the questions.
When It gives me the right message when there are less than 3 questions and when the first question had less than 3 answers, but when there are 3 questions and only the first one has answers, it still works which it should not. Does anybody know why?
Structure
class Question {
/**
* @param {string} question
* @param {string} prefix
* @param {string} description
* @param {string} display
* @param {string} answerType
* @param {string} multiSelect
* @param {Answer[]} answers
*/
constructor(question = "", prefix = "", description = "", display = "", answerType = "", multiSelect = "",
answers = []) {
this.question = question;
this.prefix = prefix;
this.description = description;
this.display = display;
this.answerType = answerType;
this.multiSelect = multiSelect;
this.answers = answers;
}
}
class Answer {
constructor(id = "", name = "") {
this.id = id;
this.name = name;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

