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
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.
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.
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.
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'
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With