본문 바로가기

Java Scripts/Vue.js

Vue 3 : What is yup?

728x90

validation code 를 직접 작성하는 것이 귀찮고 시간도 많이 걸리는 작업이기 때문애  YUP package 를 이용하면 된다.

 

Vee-validate recommends as a best practice to use the library Yup https://github.com/jquense/yup in order to create our validation schemas.

 

 

https://github.com/jquense/yup

 

GitHub - jquense/yup: Dead simple Object schema validation

Dead simple Object schema validation. Contribute to jquense/yup development by creating an account on GitHub.

github.com

 

Installing Yup

npm install yup
// or
yarn add yup

 

ComponentsForm.vue

import * as yup from 'yup'

 

Rewriting the validationSchema

YUP has the ability to create both array- and object-based schemas, but veevalidate is expecting an object with a property for each one of our form fields.

YUP은 배열 기반 스키마와 객체 기반 스키마를 모두 생성할 수 있지만 veevalidate는 각 양식 필드에 대한 속성이 있는 객체를 생성한다.
Call the object function within the yup object and  set it up with an empty object that we will fill up with our validations.

YUP  객체 내에서 객체 함수를 호출하고 빈 객체를 설정하여 유효성 검사로 채게 됩니다.

 

ComponentsForm.vue

const validationSchema = yup.object({
 
})

 

Yup has a very straightforward way of defining the rules that we want for a particular field. and use the yup object and append to it as many functions that describe the validations you want for the field.

YUP 은  특정 필드에 대해 원하는 규칙을 정의하는 매우 간단한 방법이 있습니다. YUP 개체를 사용하여 필드에 대해 validation 을 설명하는 많은 함수를 여기에 추가한다.

 

ComponentsForm.vue

   const validationSchema = object({
      category: string().required(),
      title: string().required('A cool title is required').min(3),
      description: string().required(),
      location: string(),
      pets: number(),
      catering: boolean(),
      music: boolean()
    })

 

note) 위와  같은 validation scheme 이 정의되면, submit button 이 눌리게되면 잘못된 data 가 있으면 error message 가 표시된다.

 

working source codes

https://github.com/pidokige02/validating-vue3-forms-demo

 

GitHub - pidokige02/validating-vue3-forms-demo

Contribute to pidokige02/validating-vue3-forms-demo development by creating an account on GitHub.

github.com

 

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