IT, 개발/Libarary

React Hook Form Validate Error Message

  • -
반응형
           <div className="pt-2">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="confirm_password">
                        Confirm Password *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="password"
                        placeholder="************"
                        autoComplete="on"
                        {...register('confirm_password', {
                            required: true,
                            validate: (val: string) => {
                                if (watch('password') != val) {
                                    return 'Your passwords do no match';
                                }
                            },
                        })}
                    />
                    {errors.confirm_password?.type === 'required' && (
                        <p className="text-red-500 text-xs italic">Confirm Password is required</p>
                    )}
                    {errors.confirm_password?.type === 'validate' && (
                        <p className="text-red-500 text-xs italic">Confirm Password is not same Password</p>
                    )}
                </div>

React Hook Form은 React 애플리케이션에서 폼을 만들고 유효성을 검사하기 위한 간편한 방법을 제공하는 인기 있는 라이브러리입니다. 그러나 때로는 React Hook Form을 사용하는 동안 발생할 수 있는 일부 에러와 문제에 직면할 수 있습니다. 이 글에서는 React Hook Form Validate에 관련된 일반적인 에러에 대해 알아보고, 그 해결책에 대해 설명하도록 하겠습니다.

 

1. React Hook Form 소개

React Hook Form은 리액트 기반의 폼 관리 라이브러리로, 복잡한 폼 로직을 간편하게 작성할 수 있도록 도와줍니다. 이 라이브러리는 간단하면서도 성능이 우수하며, 다양한 유효성 검사 기능을 제공합니다.

 

2. React Hook Form Validate란?

React Hook Form Validate는 React Hook Form에서 제공하는 유효성 검사 기능입니다. 이를 사용하여 사용자로부터 입력받은 데이터를 검증하고, 필요한 조건에 맞지 않는 경우 에러를 처리할 수 있습니다.

react hook form validate error

3. React Hook Form Validate Error 메세지 사용법

import { useForm } from 'react-hook-form';

const RegisterComponent = () => {
 
    const {
        register,
        handleSubmit,
        watch,
        formState: { errors },
    } = useForm();
    
    console.log(data, 'react hook form data Object')
    console.log(watch('watch example')); // watch input value by passing the name of it
    
    ...
    
    return (
                <form onSubmit={handleSubmit(onSubmit)} className="max-w-md mx-auto ">
                <div className="">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="countryCode">
                        Country *
                    </label>
                    <select
                        id="countryCode"
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.countryCode ? 'border-red-500' : ''
                        }`}
                        {...register('countryCode', { required: true })}
                    >
                        <option value="">-- Select --</option>
                        {countryList.map((country) => (
                            <option key={country.code} value={country.code}>
                                {country.name}
                            </option>
                        ))}
                    </select>
                    {errors.countryCode && <span className="text-red-500 text-xs italic">Country is required</span>}
                </div>

                <div className="pt-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="name">
                        Name *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="text"
                        placeholder="Enter your name"
                        {...register('name', { required: true })}
                    />
                    {errors.name && <span className="text-red-500 text-xs italic">Name is required</span>}
                </div>
                <div className="pt-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">
                        Email *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="email"
                        placeholder="Enter your email"
                        {...register('email', { required: true })}
                    />
                    {errors.email && <span className="text-red-500 text-xs italic">Email is required</span>}
                </div>

                <div className="pt-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="homepage">
                        Homepage (SNS)
                    </label>
                    <input
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight"
                        type="text"
                        placeholder="Enter your Homepage or SNS URL"
                        {...register('homepage')}
                    />
                </div>

                <div className="pt-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
                        Password *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="password"
                        placeholder="************"
                        autoComplete="on"
                        {...register('password', { required: true, minLength: 6 })}
                    />
                    {errors.password?.type === 'required' && (
                        <span className="text-red-500 text-xs italic">Password is required</span>
                    )}
                    {errors.password?.type === 'minLength' && (
                        <span className="text-red-500 text-xs italic">Password cannot less than 6 characters</span>
                    )}
                </div>

                <div className="pt-2">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="confirm_password">
                        Confirm Password *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="password"
                        placeholder="************"
                        autoComplete="on"
                        {...register('confirm_password', {
                            required: true,
                            validate: (val: string) => {
                                if (watch('password') != val) {
                                    return 'Your passwords do no match';
                                }
                            },
                        })}
                    />
                    {errors.confirm_password?.type === 'required' && (
                        <p className="text-red-500 text-xs italic">Confirm Password is required</p>
                    )}
                    {errors.confirm_password?.type === 'validate' && (
                        <p className="text-red-500 text-xs italic">Confirm Password is not same Password</p>
                    )}
                </div>
                <div className="pt-8">
                    <Button size="xl" type="submit" classes="w-full bg-primary">
                        Submit
                    </Button>
                    By clicking the registration button, I accept the privacy policy and terms and conditions.
                </div>
            </form>


)

export default RegisterComponent

먼저 register를 사용하여 해당 Element의 종류를 지정하고, 필수 입력란에는 required를 입력한다. 에러 메세지를 표기하고 싶다면 errors...를 사용한다. 두개의 errors를 사용하고 싶다면 errors....type을 지정한다.

 

Input Password 예시

{/* 두 개 이상의 errors 메세지 표기 방법 및 required 설정란*/}                
                <div className="pt-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
                        Password *
                    </label>
                    <input
                        className={`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline ${
                            errors.name ? 'border-red-500' : ''
                        }`}
                        type="password"
                        placeholder="************"
                        autoComplete="on"
                        {...register('password', { required: true, minLength: 6 })}
                    />
                    {errors.password?.type === 'required' && (
                        <span className="text-red-500 text-xs italic">Password is required</span>
                    )}
                    {errors.password?.type === 'minLength' && (
                        <span className="text-red-500 text-xs italic">Password cannot less than 6 characters</span>
                    )}
                </div>

만약 customize validate 사용하고 싶다면 validate를 입력해준다. 아래의 예시는 confirm password는 password와 일치해야한다는 설정이다.

 

 
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.