0

I got an input field, which I want to be live validated. As its only one single field, I would like to avoid using a whole library for vue form validations.

There are three things I would like to accomplish:

  1. The input field is valid, if there is a first name, a space and a last name. For example a c is valid, while a is not. Although a b c is valid.
  2. The input field is wrapped inside a #wrapper, which should use valid or invalid, depending on the validation
  3. If the user tries to send a invalid string (by clicking the button or pressing enter) the .alert should show.

I have tried to write a vue script:

computed: {
  inputClass: function () {
    var inputField=document.getElementById("inputField").value;
    if (inputField==null || inputField=="") {
      return 'invalid';
    } else {
      return 'valid';
    }
  }
}

Sadly, this script always returns 'valid', even when the input field is empty.

As I am using vue.js for some other reasons, it seems a good idea to implement this inside my vue app. But I could although use jQuery. I have tried to solve the third need of my list with the following script:

$('button').on('click', function(){
  if( $(this).val().length === 0 ) {
    $('.alert').fadeIn();
  } else {
    $('.alert').hide();
  }
});

To make it easier to understand I have created a JS Bin with the HTML markup and code.

1 Answer 1

1

You should go through the vuejs documentation, it seems you don't really have a grasp of what the framework is about.

A computed variable will only be recalculated when the data of the instance will be updated. Here, there's no way to react to anything therefore the inputClass will never get computed again.

I've modified your example to bind your input to the instance.

I declared it in the data propriety and in the html as a v-model.

var app = new Vue({
  el: '#app',
  data: {
    "input": "",
  },
  computed: {
    inputClass: function () {
      var inputField=document.getElementById("inputField").value;
      if (this.input === "") {
        return 'invalid';
      } else {
        return 'valid';
      }
    }
  }
});



      <input v-model="input" type="text" placeholder="Type your full name..." id="inputField">

Now it's working

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

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.