Vue 3 : Lazy Validation
A common requirement in forms is to have the ability to only trigger the validation of a certain field whenever the user is done typing, this is called lazy validation.
지연 유효성 검사는 사용자가 특정필드의 입력을 완료할 때마다 특정 필드의 유효성 검사만 트리거하는 기능임
Text and email input fields fire different events depending on how the user interacts with them. The input event fires every time the user adds or deletes a character into the field, the change event fires once the field loses focus.
텍스트 및 이메일 입력 필드는 사용자가 상호 작용하는 방식에 따라 다른 이벤트를 발생시킵니다. input 이벤트는 사용자가 필드에 문자를 추가하거나 삭제할 때마다 실행되고, change이벤트는 필드가 포커스를 잃으면 실행됩니다.
Listening to change and not input
We are going to remove the v-model binding, so ahead and delete that from the first BaseInput that holds our email binding.
우리가 할 일은 v-model 바인딩을 제거하는 것이므로 이메일 바인딩을 보유하고 있는 BaseInput에서 이를 삭제합니다..
<BaseInput
label="Email"
type="email"
v-model="email"
:error="emailError"
/>
은 input event 를 기반으로 설계되어 있는데 이부분을 change event 에 반응하도록 변경한다.
<BaseInput
label="Email"
type="email"
:error="emailError"
:modelValue="email"
@change="handleChange"
/>
Handling the change
We need to inform vee-validate that a change in our state for the email field has occurred whenever the user changes something in the field.
사용자가 무언가를 변경할 때마다. 이메일 필드의 상태가 변경되었음을 Vee-validate에 알려야 합니다.
vee-validate provides it out of the box out of the useField composable. (handleChange)
vee-validate는 useField 컴포저블에서 바로 사용할 수 있는 기능을 제공합니다.
This function will handle all the required logic for vee-validate to update the state internally once it's called with the new value - which is exactly what our @change="handleChange" binding will do.
이 함수는, 새로운 값으로 호출되면, 내부적으로 상태를 업데이트하기 위해 vee-validate에 필요한 모든 로직을 처리합니다. 이것이 바로 @change="handleChange" 바인딩이 수행하는 작업입니다.
LoginForm.vue
<script>
import { useField, useForm } from 'vee-validate'
export default {
setup () {
function onSubmit () {
alert('Submitted')
}
const validations = {
email: value => {
if (!value) return 'This field is required'
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if (!regex.test(String(value).toLowerCase())) {
return 'Please enter a valid email address'
}
return true
},
password: value => {
const requiredMessage = 'This field is required'
if (value === undefined || value === null) return requiredMessage
if (!String(value).length) return requiredMessage
return true
}
}
// tell vee-validate that we want it to use this object as the validation’s schema.
useForm({
validationSchema: validations
})
const { value: email, errorMessage: emailError, handleChange } = useField('email')
const { value: password, errorMessage: passwordError } = useField('password')
// using JavaScript object destructuring to extract the value and errorMessage out of the password field object
// It seems like 'email' and 'password' should match with email and password within validations.
return {
onSubmit,
email,
emailError,
password,
passwordError,
handleChange
}
}
}
</script>
working codes is here
https://github.com/pidokige02/validating-vue3-forms-demo/tree/L6_lesson
GitHub - pidokige02/validating-vue3-forms-demo
Contribute to pidokige02/validating-vue3-forms-demo development by creating an account on GitHub.
github.com