如何將 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

如何將 Focus 自動跳到 VeeValidate 驗證錯誤欄位 ?

  1. 按下 Submit 後使用 alert() 顯示錯誤訊息。

如何將 Focus 自動跳到 VeeValidate 驗證錯誤欄位 ?

  1. 將 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 上找到


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

The Apache Modules Book

The Apache Modules Book

Nick Kew / Prentice Hall PTR / 2007-02-05 / USD 54.99

"Do you learn best by example and experimentation? This book is ideal. Have your favorite editor and compiler ready-you'll encounter example code you'll want to try right away. You've picked the right......一起来看看 《The Apache Modules Book》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具