I have followed a nice tutorial about HTML 5 form validation with Vue.js, and I tried too many times to add a message error next to the failed input but I couldn't. this is the tutorial : https://logaretm.com/blog/2019-05-03-html-aided-vuejs-form-validation/
This is my code:
function updateMessage(el, vm) {
vm.errors = Object.assign({}, vm.errors, {
[el.name]: el.validationMessage
});
}
export const ValidateMixin = {
data: () => ({
errors: {}
}),
computed: {
hasErrors() {
// Check if we have errors.
return Object.keys(this.errors).some(key => {
console.log(this.errors)
return !!this.errors[key];
});
}
},
directives: {
validate: {
bind(el, _, vnode) {
const vm = vnode.context;
el.addEventListener("input", e => {
updateMessage(e.target, vm);
});
vnode.context.$on("validate", () => {
updateMessage(el, vm);
});
}
}
},
methods: {
validate() {
this.$emit("validate");
}
}
};
i would like to show the error message in a span next to each input field
The mixin's
errors
object property contains a map of elementname
to validation error messages for that element. For example, entering an invalid email address into the input for<input name="myEmail" type="email" v-validate>
would create a validation message inerrors.myEmail
.You could use that
errors
object in the template to bind an element's error messages to aspan
next to the correspondinginput
:demo