How can i validate email in vuejs?

Viewed 2325

regex rule for email validation is not working in vuejs

<div class="input-wrapper">
<div class="email-icon"></div>

<input type="email"  v-model.trim="$v.email.$model"
 v-validate="'required'"
:class="{ 'is-invalid': validationStatus($v.email) }"
 name="email" class=" input-section" 
placeholder="Enter your company email ID"
:maxlength="maxemail"
v-on:keypress="validEmail($event)"
 id='email'  v-model='email' />
 
<div v-if="!$v.email.required" class="invalid-feedback">
The email field is required.</div>
                 
<div v-if="!$v.email.maxLength" class="invalid-feedback-register">
 30 characters only  {{ $v.user.password.$params.maxLength.min }} </div>
</div>

I tried checking with regex rule for email validation is not working in vuejs but unable to solve the issue.

I want email to mandatory to check domain name, example:- abc@gmail.com, tried taking one keypress event where i am unable to passs regex as given in the link

1 Answers

I always use Vuelidate. Easy and simple. You can do the maxlength and much more! Additionally, you are even able to check, which parts are 'dirty' in the Vue Devtools! Example code:

<template>
   <input required="required" v-model="email" :error-messages="emailErrors"
   @input="$v.email.$touch()" @blur="$v.email.$touch()" label="Email*"
   prepend-icon="mdi-email"></input>
</template>

<script>
import { validationMixin } from 'vuelidate'
import { required, email, ... } from 'vuelidate/lib/validators'
import { mapActions } from "vuex";
export default {

mixins: [validationMixin],
validations: {
    ...,
    email: { required, email },
    ...
},
data: () => ({ email: '', ... })
computed: {
    emailErrors () {
        const errors = []
        if (!this.$v.email.$dirty) return errors
        !this.$v.email.email && errors.push('Must be valid e-mail')
        !this.$v.email.required && errors.push('E-mail is required')
        return errors
    },
}
Related