How to display text-field validation check result in snackbar of Vuetify.js?

Viewed 1294

I have made customer form in my project. One of the function, I want to make validation function. If I just use vuetify validate method, it would be easy way but, I have to display validation message as snackbar and each text-field.

I don't have any ideas to display validation error messages in snackbar. I have tried to make test code below. Does someone help me?

    <template>
  <v-form
    ref="form"
    lazy-validation
  >
    <v-text-field
      v-model="name"
      :counter="10"
      :rules="nameRules"
      label="Name"
      required
    ></v-text-field>

    <v-text-field
      v-model="email"
      :rules="emailRules"
      label="E-mail"
      required
    ></v-text-field>

    <v-btn
      color="success"
      class="mr-4"
      @click="validate()"
    >
      Validate
    </v-btn>
        <v-snackbar v-model="snackbar" :top="true">
            <v-btn @click="dialog=false">close</v-btn>
        </v-snackbar>
  </v-form>
</template>
<script lang="ts">
import {Vue} from 'nuxt-property-decorator'
export default class extends Vue{
    dialog:boolean=false
    snackbar:boolean=false
    name:string=""
    nameRules= [
        (v:string) => !!v || 'Name is required',
        (v:string) => (v && v.length <= 10) || 'Name must be less than 10 characters',
    ]   
    email:string=""
    emailRules= [
        (v:string) => !!v || 'E-mail is required',
        (v:string) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
    ] 
    validate(){
        const validationResult=(<any>this.$refs.form).validate()
        if(!validationResult){
        return (this.snackbar = true) 
        }
    }
}
</script>
1 Answers

Add a message data in your snackbar component.

 <v-snackbar v-model="snackbar" :top="true">
    {{ text }}
    <v-btn @click="dialog=false">close</v-btn>
 </v-snackbar>

In your data

data(){
    return {
       text: null
    }
}

In your validation method

    const validationResult=(<any>this.$refs.form).validate()
    if(!validationResult){
        this.text = "Error validation"   // or get the validation error message 
        this.snackbar = true
    }
Related