2

I have an input field where I validate if the input field is empty or not. If it is empty, then I will apply a red border to input using class binding.

After that, when the user focuses on input after getting the error, the error should go away. However, it is not working as expected. It doesn't actually remove the error.

new Vue ({
el: '#app',
  data: {
      register: {
        firstName: '',
      },
      errors: {
        firstName: '',
      },
  },
  methods: {
    validateLoginForm() {
      const regsrt = this.register;

      this.errors = {};

      if(!regsrt.firstName) {
        this.errors.firstName = 'First Name is required';
      } else {
        this.errors.firstName = '';
      }
    },
    deleteErrors(errorName) {
      this.errors[errorName] = '';
    }
  }
});
<div id = "app">
  <form action="" method="POST" accept-charset="UTF-8" @submit.prevent="validateLoginForm()">
      <label for="firstName">First Name</label>
        <input 
            :class = "{'red-border': errors.firstName}" 
            type="text" 
            @focus="deleteErrors('firstName')"
            v-model="register.firstName">
        <input type="submit" value="Register">
  </form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>

JSFiddle: http://jsfiddle.net/6L3shqdk/14/

As you can see, when the input gets focused, the error with firstName should be empty such that the class applied using binding should set to false and go away. But it's not happening. Please help!

1 Answer 1

3

Remove this line

this.errors = {};

It completely destroys reactive capabilities. It basically overwrites object that has necessary setters (for firstName property) with a new blank object, that can't watch firstName changes anymore.

It should be like this:

validateLoginForm() {
  const regsrt = this.register;

  if (!regsrt.firstName) {
    this.errors.firstName = 'First Name is required';
  } else {
    this.errors.firstName = '';
  }
},
Sign up to request clarification or add additional context in comments.

1 Comment

Got it! +1 for the explanation :)

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.