Two fields named text and email are included in my template. Below is the structure of the template:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Vue - Validations</title>
<script src="Libraries/vue/vue.min.js"></script>
<script src="Libraries/vue/vuelidate.min.js"></script>
<script src="Libraries/vue/validators.min.js"></script>
</head>
<body>
<div id="app">
<h2>Form Validation</h2>
<input v-model="text" v-on:blur="$v.text.$touch()" :class="status($v.text)">
<p style="color:red;">{{textErrMsg}}</p>
<input v-model="email" v-on:blur="$v.email.$touch()" :class="status($v.email)">
<p style="color:red;">{{emailErrMsg}}</p>
<pre>{{ $v }}</pre>
</div>
<script src="app.js"></script>
</body>
</html>
JS
Vue.use(window.vuelidate.default)
const { required, minLength,email, numeric, minValue } = window.validators
new Vue({
el: "#app",
data: {
text: '',
email: '',
textErrMsg: '',
emailErrMsg: ''
},
validations: {
text: {
required,
minLength: minLength(5)
},
email: {
required,
email
}
},
methods: {
status(validation) {
return {
error: validation.$error,
dirty: validation.$dirty
if(validation.text.required){
this.textErrMsg == "Text is required";
} else if(validation.text.minLength){
this.textErrMsg == "Text must be 5 characters";
}
if(validation.email.required){
this.emailErrMsg == "Email is required";
} else if(validation.email.email){
this.emailErrMsg == "Enter valid email";
}
}
}
}
})
The goal is to detect validation failure conditions such as required, email, minLength, etc., in the JavaScript file so that appropriate messages can be displayed in the template.
Instead of handling this directly in the template.
<p>{{!$v.text.required ? 'Text is required': !$v.text.minLength ? 'Text must be 5 characters' : '' }}</p>