• Home
  • Công nghệ
  • Sử dụng React hook form + Yup để quản lí và Validate form trong 1 dự án react.

Sử dụng React hook form + Yup để quản lí và Validate form trong 1 dự án react.

Trong một dự án react việc quản lý form có thể trở nên phức tạp, đặc biệt khi yêu cầu xác thực dữ liệu và tối ưu hóa hiệu suất. Trong bài viết này, chúng ta sẽ cùng tìm hiểu cách kết hợp React Hook FormYup để xây dựng một form hiệu quả và thân thiện với người dùng.

2. Cài đặt

Để bắt đầu, cài đặt các thư viện :

				
					npm install <a href="https://fstack.io.vn/blog/react-hook-form-1-giai-phap-hieu-qua-de-quan-ly-form/">react-hook-form</a> yup @hookform/resolvers

				
			

3. Tạo Form với React Hook Form

Hãy cùng tạo một form đăng ký đơn giản với các trường thông tin: name, email, và password. Chúng ta sẽ sử dụng React Hook Form để quản lý state của form và Yup để xác thực các giá trị nhập vào.

3.1. Định nghĩa Schema

				
					// validationSchema.js
import * as yup from 'yup';

export const schema = yup.object().shape({
  name: yup.string().required('Name is required'),
  email: yup.string().email('Invalid email format').required('Email is required'),
  password: yup
    .string()
    .min(6, 'Password must be at least 6 characters')
    .required('Password is required'),
});

				
			

3.2. Tạo Component RegisterForm

Trong component RegisterForm, chúng ta sử dụng React Hook Form để quản lý form và tích hợp Yup để xác thực dữ liệu.

				
					import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { schema } from './validationSchema';
import './styles.css'; // Import file CSS để cải thiện <a href="https://fstack.io.vn/blog/du-an/">giao diện</a>

const RegisterForm = () => {
  const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: yupResolver(schema),
  });

  const onSubmit = (data) => {
    alert('Registration Successful');
    console.log('Form data:', data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Name:</label>
        <input {...register('name')} />
        {errors.name && <p className="error-message">{errors.name.message}</p>}
      </div>

      <div>
        <label>Email:</label>
        <input {...register('email')} />
        {errors.email && <p className="error-message">{errors.email.message}</p>}
      </div>

      <div>
        <label>Password:</label>
        <input type="password" {...register('password')} />
        {errors.password && <p className="error-message">{errors.password.message}</p>}
      </div>

      <button type="submit">Register</button>
    </form>
  );
};

export default RegisterForm;

				
			

4. Giải thích từng phần

4.1.Khai báo thư viện và schema:

4.2.useFoem Hook:

				
					const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: yupResolver(schema),
});

				
			

4.3.onSubmit Handler:

				
					const onSubmit = (data) => {
  alert('Registration Successful');
  console.log('Form data:', data);
};

				
			

onSubmit là hàm xử lý khi form hợp lệ và được submit thành công. Dữ liệu sẽ được in ra console và hiển thị thông báo thành công.

4.4. Giao diện form

				
					<form onSubmit={handleSubmit(onSubmit)}>
  <div>
    <label>Name:</label>
    <input {...register('name')} />
    {errors.name && <p className="error-message">{errors.name.message}</p>}
  </div>

  <div>
    <label>Email:</label>
    <input {...register('email')} />
    {errors.email && <p className="error-message">{errors.email.message}</p>}
  </div>

  <div>
    <label>Password:</label>
    <input type="password" {...register('password')} />
    {errors.password && <p className="error-message">{errors.password.message}</p>}
  </div>

  <button type="submit">Register</button>
</form>

				
			

5. Kết luận

Ở trên là 1 số chia sẻ về cách kết hợp giữa react hook form và Yup của mình, vì đây đa phần là kiến thức mình tự học nên có thể bài viết này có thể có nhiều chỗ chưa chính xác và thiếu sót, mong mọi người góp ý ở dưới phần bình luận để bài viết thêm hoàn chỉnh và xây dựng một cộng đồng nơi mọi người có thể chia sẻ kinh nghiệm lập trình cho nhau 😘.

Bài viết liên quan

Building a High-Converting Shopify Product Page: Design, Copy, and Psychology

Your Shopify product page is the digital storefront where potential customers decide whether to make a purchase. It’s…

ByByAuto Mation Dec 30, 2025

The Impact of Page Speed on Conversions: Optimizing Your Shopify Store for a Faster User Experience

In the fast-paced world of e-commerce, every second counts. A slow-loading Shopify store can be the difference between…

ByByAuto Mation Dec 29, 2025

Shopify Order Routing: How to Ship From Multiple Warehouses Efficiently

In today’s competitive e-commerce landscape, efficient order fulfillment is crucial for customer satisfaction and business success. For Shopify…

ByByAuto Mation Dec 29, 2025

Shopify SEO Beyond Keywords: Optimizing for Voice Search and Visual Discovery

In the ever-evolving landscape of e-commerce, staying ahead of the curve is paramount for Shopify store owners. While…

ByByAuto Mation Dec 29, 2025

Subscribe
Thông báo của
guest

0 Comments
Cũ nhất
Mới nhất Được bình chọn nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận

0
Rất mong nhận được suy nghĩ của bạn, vui lòng bình luận.x
()
x