I want to validate an input textbox. When users enter anything in the textbox, it will validate and show error message according to the result.
I need to use Debounce here to reduce validation rate.
validateText = _.debounce(() => { if ( this.input.passwordConfirmation.length > 0 && this.input.password !== this.input.passwordConfirmation ) { this.isPasswordSame = false; } else { this.isPasswordSame = true; } console.log('Same: ' + this.isPasswordSame); console.log('Valid: ' + this.isPasswordValid); }, 500);
Then I bind this function to onChange.
Finally, I bind the validation result to a div for error message.
Password and confirmed password is not the same
… WTH …. it does not work.
The reason is that Vue does not work well with arrow function () =>.
So we need to make sure that scope of
this.isPasswordSame
is correct.
Let’s make a simple modification like this.
First declare a validator function as methods. Then pass that function to debounce.
validator() { if ( this.input.passwordConfirmation.length > 0 && this.input.password !== this.input.passwordConfirmation ) { this.isPasswordSame = false; } else { this.isPasswordSame = true; } if (this.input.password.length < 8) { this.isPasswordValid = false; } else { this.isPasswordValid = true; } console.log('Same: ' + this.isPasswordSame); console.log('Valid: ' + this.isPasswordValid); } validateText = _.debounce(this.validator, 500);
It works !!!
https://www.youtube.com/watch?v=QSOG8PvBq5g