我的模板包含 2 个字段,称为text、email。模板如下图所示
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>{{!$v.text.required ? 'Text is required': !$v.text.minLength ? 'Text must be 5 characters' : '' }}</p>-->
<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
// Want to perform somethins like this
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";
}
}
}
}
})
如 js 文件中所述,我想检测验证失败条件(即要求、电子邮件、minLength ...),以便我可以在模板中构建和显示适当的消息。
而不是在模板中做这些事情。
<p>{{!$v.text.required ? 'Text is required': !$v.text.minLength ? 'Text must be 5 characters' : '' }}</p>