问题
Below is my code. I would like to validate the form during submit. I prevented submit action untill all data is valid. Hence I have used "validata all()" method. If the form has null/invalid date, it should alert "not submitted".Else it should alert "submitted". My problem is that, when I clicked the submit button at first time, the alert displays as "submitted" instead of "not submitted" Result1. But when I clicked the same button for the second time or further it displays correctly as "not submitted" Result2. I don't know the reason, why it's not working in the first time.
<template>
<div id="app">
<h1>Add Items</h1>
Product Name :
<input type="text" name="product" v-validate="'required|alpha_dash'" >
<span style="color:red;">{{errors.first('product')}}</span>
<br>
Product Price :
<input type="number" name="price" v-validate="'required|min_value:100|max_value:500'">
<span style="color:red;">{{errors.first('price')}}</span>
<br>
<button @click="submit">Save</button>
</div>
</template>
<script>
import Vue from 'vue'
import VeeValidate from 'vee-validate'
Vue.use(VeeValidate)
export default {
name: 'addEmpl',
methods: {
submit() {
this.$validator.validateAll()
if (!this.errors.any()) {
alert('submitted')
}else{
alert('not submitted')
}
}
}
}
</script>
回答1:
Try .then(...)
after validateAll()
method:
this.$validator.validateAll().then((result) => {
if(!result){
alert('not submitted')
return
}
alert('submitted')
}).catch(() => {
// error check if needed
})
Also, there is an issue for a case alike here on Github page. You can have a look.
来源:https://stackoverflow.com/questions/50151874/javascript-functions-are-not-working-properly-in-the-vuejs