ブログの投稿ログ

2021年
9月
8月
7月
6月

メール 電話番号のバリデーション

でも

// HelloWorld.vue

<template>
  <div class="watcher">
    <h2>Watchの検証</h2>
    <div id="watchForm">
      <h3>MailAddress</h3>
      <p><input type="text" v-model="mail" /></p>
      <p class="error" v-if="error.mail">{{ error.mail }}</p>
      <h3>Tell</h3>
      <p><input type="text" v-model="tell" /></p>
      <p class="error" v-if="error.tell">{{ error.tell }}</p>
    </div>
  </div>
</template>

<script>
// regeMail,regeTellは正規表現を定義
const regeMail = /^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/;
const regeTell = /^(0{1}\d{1,4}-{0,1}\d{1,4}-{0,1}\d{4})$/;

export default {
  data() {
    return {
      mail: "",
      tell: "",
      error: {},
    };
  },
  watch: {
    mail: function (val) {
      if (regeMail.test(val)) {
        this.error.mail = "";
      } else if (val === "") {
        this.error.mail = "メールアドレスは必須です";
      } else {
        this.error.mail = "メールアドレスの形式に誤りがあります";
      }
    },
    tell: function (val) {
      if (regeTell.test(val)) {
        this.error.tell = "";
      } else if (val === "") {
        this.error.tell = "電話番号は必須です";
      } else {
        this.error.tell = "数字のみで記入してください";
      }
    },
  },
};
</script>

<style scoped>
.error {
  color: red;
  font-size: 12px;
}
</style>