1๐
โ
You need to invoke validateName
when the input value changes and when the form is submitted.
Update your HTML:
<input id="name" v-model="name" class="form-control" :class="{ 'is-invalid': isNameInvalid }" @input="validateName"/>
and your vue component:
export default {
data() {
return {
name: '',
isNameInvalid: false,
};
},
methods: {
submitForm() {
this.validateName();
if (!this.isNameInvalid) {
//submit form
}
},
validateName() {
this.isNameInvalid = this.name.trim() === '';
},
},
}
This will trigger validateName on every input change and form submission, checking if the name field is empty.
Hope this helps!
๐คAli Bahrami
0๐
There are different ways, I would suggest to use watch.
Already defined data name
property and v-model
automatically update name
. It would be better if we add watch
to name
and trigger/show invalid message.
export default {
data() {
return {
name: '',
isNameInvalid: false,
};
},
watch: {
name: {
immediate: true,
handler(value) {
validateName();
}
}
}
methods: {
submitForm() {
this.validateName();
if (!this.isNameInvalid) {
//submit form
}
},
validateName() {
this.isNameInvalid = this.name.trim() === '';
},
},
}
Template will be same as you used.
๐คWaqas Ahmed
Source:stackexchange.com