Vue (Vuetify) v-from, v-text-field 에서 유효성 검사 하기
2021. 9. 1. 13:19ㆍVue
Vuetify에서 v-text-field에 유효성 규칙을 지정하는 방법
1. v-text-field 생성
v-text-field를 만든다.
<v-text-field
v-model="email"
label="이메일"
required
:rules="emailRule"
value=""
/>
<v-text-field
v-model="password"
:append-icon="passwordShow ? 'mdi-eye' : 'mdi-eye-off'"
:type="passwordShow ? 'text' : 'password'"
label="비밀번호"
:rules="passwordRule"
counter
@click:append="passwordShow = !passwordShow"
/>
:rules에 가져올 규칙이름을 넣어준다
2. 규칙 생성
data: () => ({
email: '',
password: '',
passwordShow: false,
autoLoginCheckBox:false,
emailRule:[
v => !!v || '이메일을 입력해주세요.',
v => {
const replaceV = v.replace(/(\s*)/g, '')
const pattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/
return pattern.test(replaceV) || '이메일 형식으로 입력해주세요'
}
],
passwordRule:[
v => !!v || '비밀번호를 입력해주세요.',
v => {
const replaceV = v.replace(/(\s*)/g, '')
return replaceV.length >= 8 || '8자리 이상 입력해주세요.'
}
]
})
email field 규칙 password field 규칙을 data에 배열 형식으로 만든다.
v : 필드에 들어간 데이터
!!v : 필드에 데이터가 없을 때
replace(/(\s*)/g, '') : 필드에 들어간 모든 빈칸을 제거
* 필드에 빈칸이 들어가면 데이터를 유효성검사를 제대로 못 할 경우가 생길 수 있기 때문에 사용
pattern : 이메일 정규식으로 만들어 적용
3. 유효성 검사 후 submit
설정 한 유효성을 체크 한 후 모두 통과해야 submit 해야한다.
<v-form
ref="form"
@submit.prevent="login"
>
<v-text-field
v-model="email"
label="이메일"
required
:rules="emailRule"
value=""
/>
<v-text-field
v-model="password"
:append-icon="passwordShow ? 'mdi-eye' : 'mdi-eye-off'"
:type="passwordShow ? 'text' : 'password'"
label="비밀번호"
:rules="passwordRule"
counter
@click:append="passwordShow = !passwordShow"
/>
<v-checkbox
v-model="autoLoginCheckBox"
:label="'자동 로그인'"
/>
<v-btn
id="login_btn"
@click="login"
@keyup.enter="login"
>
로그인
</v-btn>
</v-form>
v-form 태그에 ref="form"를 넣어준다.
methods:{
async login(){
const validate = this.$refs.form.validate()
if (validate){
const email = this.email.replace(/(\s*)/g, '')
const password = this.password.replace(/(\s*)/g, '')
await this.$store.dispatch('LOGIN', { email, password, saveLogin:this.autoLoginCheckBox })
}
}
}
submit하는 함수에서 this.$refs.form.validate()가 true인지 false인지 확인 후 true일때 submit을 하도록 if문을 걸어주어 실행하면된다.
728x90
반응형
'Vue' 카테고리의 다른 글
Vuex 새로고침 시 데이터 초기화 막기 [ vuex-persistedstate (세팅) 설명 ] (0) | 2021.09.11 |
---|---|
Vuex (설치/셋팅) 설명 (0) | 2021.09.11 |
Vue-router 설정 / 네비게이션 가드 하는 방법 (0) | 2021.08.25 |
Vue, Pagination, Vuetify table을 이용한 페이징 네이션 (0) | 2021.02.24 |
Vue Interceptor 설정하여 Authorization 값 넣기 (0) | 2020.10.28 |