Search code examples
vuelidatevetur

How to validate email addresses using vuelidate?


How to validate emails?

Would you please show an example with an error message?

Documentation does not give enough details.

It seems there is nothing like v-if="!$v.user.email.email"

Following code does not work either

validations: {
 user: {
  email: {
        required,
        email: email(),
      },
 }
}

Solution

  • Actualy, I was wrong and there was something like v-if="!$v.user.email.email" You do not need any details for email validator.

    All you need is

     email: {
            email,
          },
    

    If you had any Vetur errors just uninstall Vetur and reinstall it.

    Vue.use(window.vuelidate.default)
    const { email } = window.validators
    
    new Vue({
        el: "#app",
      data: {
        user: {
         email: ""
        }
      },
      validations: {
        user:{
            email: {
              email
            }
        }
      },
      methods: {
        status(validation) {
            return {
            error: validation.$error,
            dirty: validation.$dirty
          }
        }
      }
    })
    input {
      border: 1px solid silver;
      border-radius: 4px;
      background: white;
      padding: 5px 10px;
    }
    
    .dirty {
      border-color: #5A5;
      background: #EFE;
    }
    
    .error {
      border-color: red;
      background: #FDD;
    }
    <script src="https://cdn.jsdelivr.net/combine/npm/[email protected]/dist/validators.min.js,npm/[email protected]/dist/vuelidate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <input v-model="$v.user.email.$model" :class="status($v.user.email)">
       <div class="error" v-if="!$v.user.email.email">this must be an email</div>
      <pre>{{ $v }}</pre>
    </div>


    Answer https://stackoverflow.com/a/61359412/11993949 shows off how to use on blur functionality too