1

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??

5
  • have you tried chrome dev tool for debug? Commented Feb 25, 2020 at 6:29
  • @ShahadatHossain Yep I'm using it for debugging Commented Feb 25, 2020 at 6:30
  • I mean after blur your input, have you seen that errors.username data update or not? Commented Feb 25, 2020 at 6:37
  • @ShahadatHossain Yes , It doesn't update until I write in any input Commented Feb 25, 2020 at 6:39
  • see my solution. I think it will solve Commented Feb 25, 2020 at 6:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.