如何將 Focus 自動跳到 VeeValidate 驗證錯誤欄位 ?
栏目: JavaScript · 发布时间: 7年前
内容简介:實務上在驗證欄位時,不單單只是顯示錯誤訊息而已,實務上可能會需要Vue 2.5.17VeeValidate 2.1.2
實務上在驗證欄位時,不單單只是顯示錯誤訊息而已,實務上可能會需要 alert() 顯示錯誤訊息,還必須要將 Focus 回到錯誤欄位,VeeValidate 內建並沒有支援此功能,必須自行實作。
Version
Vue 2.5.17
VeeValidate 2.1.2
User Story
- 按下
Submit後使用alert()顯示錯誤訊息。
- 將 focus 回到錯誤的欄位上
VeeValidate
demo.vue
<template>
<div>
<div>
<input v-model="customEmail"
v-validate="'required|custom-email'"
name="customEmailAddress"
type="text">
</div>
<div>
<span>{{ errors.first('customEmailAddress') }}</span>
</div>
<div>
<button @click="onSubmit">Submit</button>
</div>
</div>
</template>
<script>
import validator from '../validators/email';
validator();
/** data */
const data = function() {
return {
email: '',
customEmail: '',
};
};
/** methods */
const onSubmit = function() {
const hasError = this.errors.items.length;
const showFirstErrorMessage = () => alert(this.errors.items[0].msg);
const name = this.errors.items[0].field;
const setFocusOnErrorComponent = () => this.$root.$el.querySelector(`[name=${name}]`).focus();
if (hasError) {
showFirstErrorMessage();
setFocusOnErrorComponent();
return;
}
alert('no error');
};
const methods = {
onSubmit,
};
export default {
name: 'demo',
data,
methods,
};
</script>
33 行
const hasError = this.errors.items.length;
VeeValidate 的 errors object 會在 Vue Instance 下,而所有錯誤訊息都在 items array 下。
由於 ECMAScript 的 Truthy Value 特性,因此可用 length 作為 true 判斷。
34 行
const showFirstErrorMessage = () => alert(this.errors.items[0].msg);
其中第一個錯誤訊息,就是放在 items[0].msg property。
35 行
const name = this.errors.items[0].field;
const setFocusOnErrorComponent = () => this.$root.$el.querySelector(`[name=${name}]`).focus();
除了顯示錯誤訊息外,我們還希望將 focus 回到錯誤欄位。
由於 VeeValidate 都要使用 HTML 的 name ,因此我們可利用此特性抓到錯誤欄位。
使用 items[0].field 抓到第一個錯誤欄位的 name 。
利用 this.$root.$el 的 querySelect() 抓到該欄位,然後呼叫 focus() 。
38 行
if (hasError) {
showFirstErrorMessage();
setFocusOnErrorComponent();
return;
}
若有任何 VeeValidate 驗證錯誤,使用 alert() 顯示錯誤訊息,並將 focus 回到錯誤欄位,一氣呵成。
Conclusion
- VeeValidate 並沒有內建此功能,必須使用一些小技巧才能達成
Sample Code
完整的範例可以在我的 GitHub 上找到
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming Rust
Jim Blandy / O'Reilly Media / 2016-8-25 / GBP 47.99
This practical book introduces systems programmers to Rust, the new and cutting-edge language that’s still in the experimental/lab stage. You’ll learn how Rust offers the rare and valuable combination......一起来看看 《Programming Rust》 这本书的介绍吧!