I am using BootstrapVue and VeeValidate in my Laravel + Vue.js SPA (Single Page Appplication). When form fields are invalid, it automatically shows errors in respective positions. But I need a way so that whenever any form input is invalid I can show a message ( i.e. 'Invalid data') within a div
with id
result
just above the form
.
My Register.vue
component has the following form :
<template>
<ValidationObserver ref="form" v-slot="{ passes }">
<div id="registration_form">
<div id="page_header" class="text-center" >Register</div>
<div id="result" v-html="result" class="result text-center"></div>
<b-form @submit.prevent="passes(onSubmit)" @reset="resetForm">
<ValidationProvider vid="name" rules="required|min:2" name="name" v-slot="{ valid, errors }">
<b-form-group
label="User Name:"
label-for="exampleInput1"
>
<b-form-input
type="text"
disable-leading-trailing-space
v-model="name"
:state="errors[0] ? false : (valid ? true : null)"
placeholder="Enter your name"
></b-form-input>
<b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
</b-form-group>
</ValidationProvider>
<ValidationProvider vid="email" rules="required|email" name="Email" v-slot="{ valid, errors }">
<b-form-group
label="Email address:"
label-for="exampleInput1"
description="We'll never share your email with anyone else."
>
<b-form-input
type="email"
disable-leading-trailing-space
v-model="email"
:state="errors[0] ? false : (valid ? true : null)"
placeholder="Enter email"
></b-form-input>
<b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
</b-form-group>
</ValidationProvider>
<b-button type="submit" variant="primary">Submit</b-button>
<b-button type="reset" variant="danger">Reset</b-button>
</b-form>
</div><!-- end of id registration_form-->
</ValidationObserver>
</template>
JS part has :
<script>
import { ValidationObserver, ValidationProvider } from "vee-validate";
export default {
name: "Register",
components: {
ValidationObserver,
ValidationProvider
},
data: () => ({
name: "",
email: "",
result:''
}),
methods: {
onSubmit() {
console.log("Form submitted yay!");
},
resetForm() {
this.name = "";
this.email = "";
requestAnimationFrame(() => {
this.$refs.form.reset();
});
}
}
};
</script>
Whenever any form
input is in invalid condition, I want to show in div
with id
result
the message 'Invalid data'.
Is there any event like beforeSubmit
or any other way to accomplish that ?
EDIT:
I also want to scroll the window to the top (window.scrollTo(0,0)
) whenever any validation error occurs in front end. How to do that ?
Grab the
failed
state from theValidationObserver
slot props: