5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

正規表現を用いたemailとパスワードのバリデーション(JavaScript)

Posted at

やりたいこと

nuxt.jsでのメールアドレスとパスワードのバリデーション
vuelidateなどのバリデーション用のライブラリを使用せずに実装したい

コード

password.vue
<template>
  <div class="#">
    <div class="#">
      <h2>
        メール・パスワード変更
      </h2>
    </div>
    <div class="#">
      <div class="#">
        <input
          v-model="email"
          type="text"
          :notes="emailErrorText"
          placeholder="メールアドレスを入力"
          @input="validateEmail"
        />
        <input
          v-model="user.pastPassword"
          :required="true"
          type="password"
          placeholder="現在のパスワードを入力"
        />
        <input
          v-model="user.password"
          type="password"
          :notes="passwordErrorText"
          placeholder="新しいパスワードを入力"
          @input="validatePassword"
        />
        <input
          v-model="user.password_confirmation"
          type="password"
          :notes="passwordConfirmationErrorText"
          placeholder="新しいパスワードを入力"
          @input="validatePasswordConfirmation"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data: () => ({
    user: {
      pastPassword: '',
      password: '',
      password_confirmation: '',
    },
    email: '',
    emailError: false,
    passwordError: false,
    passwordConfirmationError: false
  }),
  computed: {
    emailErrorText () {
      return this.emailError ? '無効なメールアドレスです' : '';
    },
    passwordErrorText () {
      return this.passwordError ? '無効なパスワードです。半角英数字を含んで8-15文字の範囲内で入力してください。' : '半角英字と半角数字を含めた8-15文字以内';
    },
    passwordConfirmationErrorText () {
      return this.passwordConfirmationError ? 'パスワードが一致していません' : '';
    },
  },
  methods: {
    validateEmail(email){
      // emailの正規表現
      const regexp = /^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/;
      console.log(regexp.test(email));
      regexp.test(email) ? this.emailError = false: this.emailError = true;
    },
    validatePassword(password){
      // 半角英数字8-15文字の正規表現
      const regexp = /^(?=.*?[a-z])(?=.*?\d)[a-z\d]{8,15}$/i;
      regexp.test(password) ? this.passwordError = false : this.passwordError = true;
    },
    validatePasswordConfirmation(conf){
      this.user.password === conf ? this.passwordConfirmationError = false : this.passwordConfirmationError = true;
    }
  }
};
</script>

5
6
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?