Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email validation n vuetify.js

I have an email field

    <template>
  <v-form v-model="valid">
    <v-text-field
      label="Name"
      v-model="name"
      :rules="nameRules"
      :counter="10"
      required
    ></v-text-field>
    <v-text-field
      label="E-mail"
      v-model="email"
      :rules="emailRules"

    ></v-text-field>
  </v-form>
</template>

and validation rule like,

 <script>
  export default {
    data: () => ({
      valid: false,
      name: '',
      nameRules: [
        v => !!v || 'Name is required',
        v => v.length <= 10 || 'Name must be less than 10 characters'
      ],
      email: '',
      emailRules: [ 
        v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
      ]
    })
  }
</script>

but it validate form whnever i submit the form, i need to validate email only when email.length>0 . ie email is not a required field, but if email typed , it must be validate.

also tried, when i change :rules="[emailRules.em]" like this and in script

emailRules: { 
                        em:v => {
                        if(v.length > 0 && /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) )
                            return ''E-mail must be valid';  
                          return true;
                    }
                    }

it always return true

like image 367
geethika Avatar asked Apr 26 '18 09:04

geethika


People also ask

How do I add validation to Vuetify?

To add Vuetify, navigate to the project folder cd vuetify-form-validation. When the Vuetify command starts running, it'll again ask to select which preset you want. Select the default preset.

What is lazy validation in Vuetify?

form.lazy-validation. From the Vuetify form API docs: If enabled, value will always be true unless there are visible validation errors. You can still call validate() to manually trigger validation. Here, value is used to represent whether the form is currently valid.

What is ref in Vuetify?

A ref allows us to access internal methods on a component, for example, <v-form ref="form"> . this.$refs.form.validate() will validate all inputs and return if they are all valid or not. this.$refs.form.reset() will clear all inputs and reset their validation errors.


1 Answers

Just add the condition !v at the begining of your rule :

 emailRules: [ 
        v => !v || /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
      ]
like image 95
Charles G Avatar answered Sep 22 '22 05:09

Charles G