Reputation: 19
I'm having a weird proplem that I can't understand
I have a registration form, and on any input I'm executing the method on blur;
<input class='form-control' placeholder='Username' @blur="watchVal" v-model="username">
Method
watchVal : function(){
if(this.username == ""){
this.errors['username'].push('Username is empty');
}
}
Data:
data: function(){
return {
username: "",
errors: {
'username' : []
}
}
}
When I blur without writing any value, nothing is added to this.errors['username']
, unless I type a letter in any field.
I've also tried to make validation on submit, but found same problem that no error is added to the array unless I type in any input,
Can anyone explain to me what I am doing wrong??
Upvotes: 1
Views: 133
Reputation: 8459
Your source is working. See in full mode if you cannot see error messages.
new Vue({
el: "#app",
data: function() {
return {
username: '',
errors: {
username: []
}
}
},
methods: {
watchVal : function(){
if(this.username == ""){
this.errors['username'].push('Username is empty');
}
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input class='form-control' placeholder='Username' @blur="watchVal" v-model="username">
<p class="text-sm text-danger" v-for="(error, index) in errors.username" :key="index">
{{ error }}
</p>
</div>
Upvotes: 0
Reputation: 979
I faced similar issue. How I solved this.
your data:
data: function(){
return {
username: "",
errors: {}
}
}
your Method
watchVal (key) {
let errors = this.errors
if (this[key] === '') {
errors[key].push('Emai empty')
}
this.errors = errors
}
your HTML
<input class='form-control' placeholder='Username' @blur="watchVal('username')" v-model="username">
<p>{{errors['username']}}</p>
You must display error variable in your HTML template then it will be solved.
Upvotes: 1