티스토리 뷰

유효성 검사가 제일 짜증 나고 귀찮은 작업이 아닐까 싶다.

 

Vuetify에선 프론트에서 처리해 줄 수 있는 유효성검사가 있어 소개하려 한다.

 

https://vuetifyjs.com/en/components/forms/

 

Vuetify — A Vue Component Framework

You are viewing the documentation for Vuetify 3

vuetifyjs.com

 

Vuetify 에선 Form태그의 유효성검사를 쉽게 해 줄 수 있는 기본 컴포넌트 하나와 2개의 써드파티가 있다.

써드파티인 Vee-validate, Vuelidate 이 두 개도 사용하기에 따라 좋은 것 같지만 굳이 기본 Rules로 처리할 수 있는데 써드파티를 깔아서 사용해야 되나 싶다.

 

간단한 예시를 보자

<template>
    <v-container>
        <v-row justify="center">
            <v-col
                    cols="12"
                    md="8"
            >

                <v-form
                    ref="form"
                >
                    <v-container>
                        <v-row>
                            <v-col
                                cols="12"
                                md="6">
                                <!-- Check Rules! -->
                                <v-text-field
                                        label="Title"
                                        v-model="boardTitle"
                                        :rules="boardTitleRules"
                                />
                            </v-col>

                            <v-col cols="12">
                                <!-- Check Rules! -->
                                <v-textarea
                                        label="Content"
                                        v-model="boardContent"
                                        :rules="boardContentRules"
                                />
                            </v-col>

                            <v-col cols="12" v-if="categoryBoard === 'ATTACHMENT'">
                                <!-- Check Rules! -->
                                <v-file-input
                                    multiple
                                    label="File input"
                                    v-model="files"
                                    :rules="fileInputRules"
                                ></v-file-input>
                            </v-col>
                        </v-row>
                    </v-container>
                </v-form>
            </v-col>
        </v-row>
    </v-container>
</template>

<script setup>

//Vuetify Validation
async function validation () {
    const { valid } = await form.value.validate();

    if (valid) postArticleSubmit();
    else {
        alert('양식을 지켜주세요.');
    }
}

const boardTitleRules = ref([
    value => {
        if (value) return true
        return '제목을 적어주세요.'
    },
    value => {
        if (value?.length > 3 && value?.length <= 100) return true
        return '제목은 4자 이상 100자 이하로 적어주세요.'
    }
])
const boardContentRules = ref([
    value => {
        if (value) return true
        return '내용을 적어주세요.'
    },
    value => {
        if (value?.length > 3 && value?.length <= 2000) return true
        return '내용은 4자 이상 2000자 이하로 적어주세요.'
    }
])
const fileInputRules = ref([
    value => {
        if (value.length > 0) return true
        return '파일을 첨부해주세요.'
    },
    value => {
        if (value.length < 4) return true
        return '파일은 최대 3개까지 가능합니다.'
    }
])
</script>

 

<script setup> 양식으로 작성했다.

title, content, 다중 파일 업로드를 위한 파일에만 유효성을 구현해 놓았다.

 

굉장히 편하지 않나 싶다.

처음엔 v-text-field에만 사용할 수 있나? 싶어서 textarea, v-file-input에도 설정해 봤는데 전부 동작했다.

 

이 상태에서 post를 보내려고 한다면

가장 중요한 건 v-form에 ref이름을 적어주는 것과

compositionApi에 맞게 호출해야 되는 걸 주의하도록 하자

 

혹시 optionApi를 사용한다면 

https://github.com/vuetifyjs/vuetify/blob/master/packages/docs/src/examples/v-form/rules-required.vue

 

GitHub - vuetifyjs/vuetify: 🐉 Vue Component Framework

🐉 Vue Component Framework. Contribute to vuetifyjs/vuetify development by creating an account on GitHub.

github.com

예제 깃허브에서 compostionApi와 optionApi를 나눠서 소개했다.

 


지켜야 할 점

가끔 유효성검사는 프런트에서만 하는 게 리소스 면에서 좋다고 하는 블로그 글을 봤다.

가장 어리석은 생각이다.

프런트의 파라미터는 언제든지 변조가 가능하다.

Vuetify의 rules를 통해서 프런트 부분의 유효성검사를 완성했다면

백엔드를 통해서도 유효성검사를 실시해 안정성을 높이도록 하자.

 

'Frontend > Vue.js' 카테고리의 다른 글

Vue.js3 Login + JWT 토큰  (0) 2023.07.11
[Vue.js3] <script> or <script setup>  (0) 2023.06.28
[Vue.js3] Pinia 란?  (0) 2023.06.19
[Vue.js3] Vuex란  (0) 2023.05.19
Vue.js3 구조 이해  (0) 2023.04.21
Comments