[Vuejs]-How to validate empty form fields

0๐Ÿ‘

You can use the v-model attribute on the input and check if its empty.

0๐Ÿ‘

You can bind v-model to inputs, and then check inside submit function, if they are empty or not. Use v-if as well. Also as someone else said, your code looks really messy.

<!DOCTYPE html>
    <header>
      <script src="https://unpkg.com/vue@next"></script>
    </header>

    <body>
      <div id="app">
        <input type="text" id="idTest">
        <form action="" onsubmit="return false" @submit="foo()">
          <input v-if="false" v-model="inputField" type="text" required placeholder="required">
          <input type="text" required placeholder="required">
          <button type="submit" onsubmit="alert('works')">send</button>
        </form>
      </div>
    </body>

    <script>

      const app = {
        mounted() {
          document.getElementById("idTest").value = Math.random().toString(36).substring(7);
        },
        data() {
          return {
            inputField: ""
        }
      },
        methods: {
          foo() {
            if(this.inputField.length < 1) {
              alert("input is empty")
            }
          }
        }
      }

      Vue.createApp(app).mount('#app');
    </script>

-1๐Ÿ‘

Try this:

 function required(inputtx) 
   {
     if (inputtx.value.length == 0)
      { 
         alert("message");      
         return false; 
      }     
      return true; 
    } 

Leave a comment