-
[vue] vee-validation yup 자바스크립트 validation 체크프론트엔드/Vuejs 2021. 9. 15. 18:05
npm install -S yup
기본사용법
import * as yup from 'yup'; let schema = yup.object().shape({ name: yup.string().required(), age: yup.number().required().positive().integer(), email: yup.string().email(), website: yup.string().url(), createdOn: yup.date().default(function () { return new Date(); }), }); // check validity schema .isValid({ name: 'jimmy', age: 24, }) .then(function (valid) { valid; // => true }); // you can try and type cast objects to the defined schema schema.cast({ name: 'jimmy', age: '24', createdOn: '2014-09-23T19:25:25Z', });
사용방식 1
<Form :validation-schema="schema"> <input v-model="data.name" /> <input type="number" v-model="data.number" /> <input v-model="data.email" /> </div> ~~~~ <button @click="onSubmit(data)" >저장</button > </Form ~~ data() { const schema = Yup.object().shape({ name: Yup.string().required("require name"), number: Yup.number().required("require num"), email: Yup.string() .email("is not email") .required("require email"), }); return { schema, data: { name: "", number: "", email: "", }, }; }, methods: { onSubmit(values) { this.schema.isValid(values).then((valid) => { // valid true or false if (valid) { alert("통과"); } else { alert("오류"); } }); },
Form 필드로 submit 을 하지 않고, 비동기식으로 전송하는 방식이고, 이 방식이 더 나은듯 하다. 이유는 아래 기입
사용방식 2
<Form @submit="onSubmit" :validation-schema="schema"> <input name="data.name" /> <input type="number" name="number" /> <input v-model="data.email" /> </div> ~~~~ <input type="submit" @click="onSubmit" >저장</input > </Form ~~ data() { const schema = Yup.object().shape({ name: Yup.string().required("require name"), number: Yup.number().required("require num"), email: Yup.string() .email("is not email") .required("require email"), }); return { schema }; }, methods: { onSubmit(values) { this.schema.isValid(values).then((valid) => { // valid true or false if (valid) { } else { } }); },
Form element 에서 submit 을 할 경우가 일반적이지만, validation 이 false 가 한개라도 있는 경우 버튼을 누르더라도 onSubmit 이벤트가 발생하지 않는다.
반응형'프론트엔드 > Vuejs' 카테고리의 다른 글
vue Quasar 에 axios 추가하기 (0) 2023.06.22 [vue] vuex binding helper - vue store 사용하기 (0) 2021.06.25 vue3 에서 vuex4 시작하기 - module 관리 (0) 2021.06.14 vue cli 실행모드 설정 및 node 환경변수 설정(NODE_ENV) (0) 2021.06.01 [vue] prop data 사용하기 - Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders - 비동기상황에서 props 데이터 사용하기 (0) 2020.11.18