In the Vue.js framework, handling real-time form validation is crucial to create a smooth and seamless user experience. To address this, you should employ reactive data properties with computed properties for validating form inputs. Here's an example of how you can achieve this:
<template>
<div class="form">
<h1>Vue Form Validation</h1>
<input type="text" v-model="username" @blur="$v.username.$touch()" placeholder="Username*"/>
<p>{{ usernameErrors[0] }}</p>
<input type="email" v-model="email" @blur="$v.email.$touch()" placeholder="Email*"/>
<p>{{ emailErrors[0] }}</p>
<textarea v-model="message" @blur="$v.message.$touch()" placeholder="Message*"></textarea>
<p>{{ messageErrors[0] }}</p>
<button :disabled="$v.$invalid">Submit</button>
</div>
</template>
<script>
import { required, email } from 'vee-validate/dist/rules';
import { validationMixin } from 'vuex-validator';
export default {
mixins: [validationMixin],
data() {
return {
username: '',
email: '',
message: ''
};
},
computed: {
...mapState({
usernameErrors: state => state.validation.username,
emailErrors: state => state.validation.email,
messageErrors: state => state.validation.message
}),
$v: mapGetters(['validation']),
isValid() {
return this.$v.$invalid;
}
},
validations: {
username: { required },
email: { email, required },
message: { required }
}
};
</script>
In the above code snippet:
- We import
required
andemail
fromvee-validate/dist/rules
to define our validation rules. - The
validationMixin
is imported fromvuex-validator
, which allows us to integrate Vue Validate into our Vuex store. - In the data properties, we initialize our form inputs with empty strings.
- We create computed properties to fetch any error messages related to each input field using the
mapState
function. - The
$v
property represents the root validation object for all fields in the form. - The
isValid
computed property checks if there are any errors by evaluating whether all fields have validations and are not touched yet ($invalid
).
By following these steps, you can real-time validate your Vue.js forms and provide feedback to the user immediately upon submission or when they blur away from an input field.