Currently, I am working on a sum application and encountering some challenges with input validations. I have implemented Watcher to handle the validations, and I am exploring the possibility of adding sound and color feedback for accurate validation.
- Repository: https://github.com/RaPzoD1/Divertinumeros
- Live Demo:
The following code snippet is used to generate random numbers for the addition operation:
created () {
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min)) + min
}
// console.log(Math.floor(Math.random() * (20 - 2)) + 2)
for (let index = 0; index < 4; index++) {
const total = getRandomInt(2, 21)
// this.numRandom.push(getRandomInt(2, 20))
const numero1 = getRandomInt(1, total)
const newObj = {
id: index,
total,
numero1,
numero2: total - numero1
}
this.numRandom.push(newObj)
}
The validation process using watchers is as follows:
watch: {
respuesta: {
handler (newValue, oldValue) {
const values = Object.values(newValue)
const operations = [...this.numRandom]
for (let i = 0; i < values.length; i++) {
if (i % 2 !== 0) {
// console.log(operations[i].numero1)
if (operations[i].numero1 === parseInt(values[i])) {
console.log('correct', operations[i].numero1, values[i])
// this.playSuccess()
// const element = document.getElementById(i)
// // console.log(element)
// element.classList.add('correct')
} else {
console.log('incorrect', operations[i].numero1, values[i])
// this.playError()
// const element = document.getElementById(i)
// element.classList.add('incorrect')
// // console.log(element)
}
} else {
// console.log(operations[i].numero2)
if (operations[i].numero2 === parseInt(values[i])) {
console.log('correct', operations[i].numero2, values[i])
// this.playSuccess()
// const element = document.getElementById(i)
// element.classList.add('correct')
// // console.log(element)
} else {
console.log('incorrect', operations[i].numero2, values[i])
// this.playError()
// const element = document.getElementById(i)
// // console.log(element)
// element.classList.add('incorrect')
}
}
}
}
}
However, the issue arises when the inputs change, causing the watchers to re-validate multiple times.
https://i.stack.imgur.com/6Hbq2.png
Any suggestions on how to improve the validation process?