Copyright © 2008 ~ 2024 MUKI space* / omegaBook theme All Rights Reserved.

介紹

表單驗證的套件有非常多種,但我覺得 HTML5 的表單驗證就已經很好用了,如果再搭配正則表達式也可以做出非常多的驗證規格。

所以在此筆記一下,如何在 VUE 裡面使用原生的 HTML5 表單驗證 (PS. VUE2 也通用喔)

表單模板

首先製作一個簡易的表單,記得一定要用 <form>...</form> 標籤,以及將 required 屬性標示在必填的欄位上。

<form>
  <p>姓名:<input type="text" required /></p>
  <p>(姓名為必填欄位)</p>
  <p>電話:<input type="text" /></p>
  <p>地址:<input type="text" /></p>
  <button @click="add">新增</button>
</form>
{{ alert }}

驗證語法

接著使用 formreportValidity() 方法,就可以幫你驗證必填的欄位是否空白。

<script>
import { ref } from "vue";
export default {
  name: "App",
  setup() {
    const alert = ref("");
    const add = (e) => {
      e.preventDefault();
      // 使用原生的 JavaScript 獲取 form 的 DOM element。
      const form = document.querySelector("form");
      if (form.reportValidity()) {
        alert.value = "送出";
      }
    };
    return { alert, add };
  },
};
</script>

使用 VUE 的 ref 獲取 DOM

如果不想用原生的 JS,我們也可以使用 VUE 的 ref 獲取 DOM。首先在 <form> 標籤增加 ref 屬性:

<!-- 在 form 標籤增加 ref 屬性 -->
<form ref="form">
  <p>姓名:<input type="text" required /></p>
  <p>(姓名為必填欄位)</p>
  <p>電話:<input type="text" /></p>
  <p>地址:<input type="text" /></p>
  <button @click="add">新增</button>
</form>
{{ alert }}

接著就跟一般使用 ref 的寫法相同,「匯入(import)」,「使用」以及「回傳(return)」:

<script>
  // 匯入 ref
  import { ref } from "vue";
  export default {
    name: "App",
    setup() {
      const alert = ref("");
       // 宣告 form
      const form = ref(null);
      const add = (e) => {
        e.preventDefault();
        // const form = document.querySelector("form");
        if (form.value.reportValidity()) {
          alert.value = "送出";
        }
      };
      // 回傳 form
      return { alert, add, form };
    },
  };
</script>

範例

以上兩種寫法,都可以做到用原生 HTML5 驗證的效果

▼ 完整範例放在 sandbox 裡

歡迎給我點鼓勵,讓我知道你來過 :)

9
Subscribe
Notify of
guest

0 則留言
Inline Feedbacks
View all comments