티스토리 뷰

https://next.vuetifyjs.com/en/api/v-text-field/

 

v-text-field API — Vuetify

API for the v-text-field component.

next.vuetifyjs.com


vuetify의 v-form validate를 이용하여 유효성 검증을 구현하였다.

v-text-filed의 rule과 v-form의 ref를 잡아주면 된다.

 

 

template

<template>
  <div>
    <v-app id="inspire" style="background-color:#FCF6F1;">
      <!-- Login Component -->
      <div class="d-flex justify-center" style="margin-top:350px">
        <v-card width="450px">
          <div class="pa-11">
            <div style="text-align: center" class="mb-16 mt-5">
              <h1>Login</h1>
            </div>
            <v-form class="pl-5 pr-5" ref="loginForm">
              <v-text-field
                class="mb-2"
                label="ID"
                :rules="userIdRule"
                v-model="username"
                prepend-inner-icon="mdi-account"
              ></v-text-field>
              <v-text-field
                class="mb-2"
                :rules="userPassRule"
                v-model="password"
                prepend-inner-icon="mdi-lock"
                type="password"
                label="Password"
              >
              </v-text-field>
              <v-btn
                @click="submitLogin"
                color="blue lighten-1 text-capitalize"
                depressed
                large
                block
                dark
                class="mb-5"
                style="height: 45px"
              >
                로그인
              </v-btn>
            </v-form>
          </div>
        </v-card>
      </div>
    </v-app>
  </div>
</template>

v-form의 ref를 loginForm으로 잡아주었다.

v-text-filed 에서 검증할 rule을 설정하면 된다.

 

setup

setup () {
    const username = ref<string>('')
    const password = ref<string>('')
    const loginForm = ref<any>(null)
    const userIdRule = ref( [
      (v: string) => !!v || '아이디는 필수 입력 사항입니다.',
      (v: string) => /^(?=.*[a-zA-Z])(?=.*[0-9]).{5,25}$/.test(v) || '영문, 숫자 조합으로 5-20자리 입력해주세요.',
    ] ) 
    const userPassRule = ref( [
      (v: string) => !!v || '비밀번호는 필수 입력 사항입니다.',
      (v: string) => /^(?=.*[a-zA-Z])(?=.*[0-9]).{5,25}$/.test(v) || '영문, 숫자 조합으로 5-20자리 입력해주세요.',
    ] )

    async function submitLogin () {
      let validate = await loginForm.value?.validate()
      // 유효
      if(validate.valid) {
        ...
      } else { // 유효 x
        return
      }
    }
}

rule에 정규식을 집어 넣는다.

 

typescript는 처음이라 v-form의 ref type 설정에서 계속 컴파일 오류가 발생했다.

일단 임시방편으로 type을 any로 설정했다.

 

정규식 출처: https://goddino.tistory.com/267

 

[js] 비밀번호 영문 숫자 조합 8자리 이상, 영문 숫자 특수기호 조합 8자리 이상 체크 (ft. 정규식)

비밀번호 유효성 검사에 사용되는 정규식입니다. 비밀번호 영문 숫자 조합 8자리 이상 (정규식) let regPass = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,25}$/; if (!regPass.test(password)) alert("영문, 숫자 조합으로 8-20자리

goddino.tistory.com