I'm trying to imitate Bootstrap form validation styling with Vue and Vee-validate.
In order to have that Boostrap validation error message, when there's a validation error, the input itself must have is-invalid
class presents. And in addition, the error message element must have invalid-feedback
class, of course.
I'm struggling to add is-invalid
class to the input when there's a validation error.
In Vee-validate 3, I was able to control the input element's classes with this guide. But it seems to be deprecated.
This is a code sandbox that you can play with. Nothing extra-ordinary, just straight out of Veevalidate example.
<template>
<div id="app">
<Form @submit="onSubmit">
<Field name="email" type="email" :rules="validateEmail" />
<ErrorMessage name="email" />
<button >Sign up</button>
</Form>
</div>
</template>
<script>
import {
Form,
Field,
ErrorMessage
} from "vee-validate";
export default {
components: {
Form,
Field,
ErrorMessage,
},
methods: {
onSubmit(values) {
console.log(values, null, 2);
},
validateEmail(value) {
// if the field is empty
if (!value) {
return "This field is required";
}
// if the field is not a valid email
const regex = /^[A-Z0-9._% -] @[A-Z0-9.-] \.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return "This field must be a valid email";
}
// All is good
return true;
},
},
};
</script>
<style>
span {
display: block;
margin: 10px 0;
}
</style>
Versions
- "vee-validate": "^4.5.11",
- "vue": "^3.2.33",
CodePudding user response:
You can render more complex fields, by utilizing the scoped slots of the <Field />
-component.
If you replace your Field-component with the following, it should work as expected:
<Field name="email" :rules="validateEmail" v-slot="{ field, errors }">
<input v-bind="field" type="email" : />
</Field>