简体   繁体   中英

How to access data that has already been validated?

Is it possible to take the data that was validated after the validation context?

<template>
  <v-text-field
    :rules="[rules.required]"
    @change='doSomething($event)'
  ></v-text-field>
</template>

<script>
export default {
  data () {
    return {
      rules: {
        required: v => !!v || 'Field required.'
      }
    }
  },
  methods: {
    doSomething (value) {
      // does something only if the data is validated
    }
  }
}
</script>

In this situation, I need to work with the data that has gone through the validation stage of the field and is valid.

I do not know how to do this in vuetify, but is there any way to get this data without having to by a function within the validation rules to do this?

You could listen the updated:error event and when the value received is false go your call.

<template>
 <v-text-field
  :rules="[rules.required]"
  @update:error='doSomething'
 ></v-text-field>

And in the script

methods: {
 doSomething (error) {
   if (error === false) {
     // model is validated
   }
 }
}

To access the fields value you should use v-model .

As you can see in my Codepen , the submit button does not work until the firstname field is valid. You can also remove lazy-validation so the button will not be clickable until it has met the validation rules.

<v-form
  ref="form"
  v-model="valid"
  lazy-validation
>
  <v-text-field
    v-model="firstname"
    :rules="nameRules"
    label="Firstname"
    required
  ></v-text-field>

  <v-btn
    :disabled="!valid"
    color="success"
    @click="doSomething"
  >
    Submit
  </v-btn>
</v-form>

And here is the script part:

<script>
  export default {
     data () {
       return {
         valid: true,
         firstname: '',
         nameRules: [v => !!v || 'Name is required']
     }
    },
    methods: {
       doSomething () {
          if (this.$refs.form.validate()) {
                 console.log(this.firstname);

          }


       },

    }
 }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM