Bài viết


Validate nhiều nhóm input trong React sử dụng useState

Ngày đăng: 24/07/2024

Thông thường để validate form trong React trước khi gửi dữ liệu tới Backend ta sẽ sử dụng Formik kết hợp với Yup để xử lý. Nhưng nếu trong form đó có nhiều nhóm input, và mỗi nhóm sẽ do người dùng thêm thủ công vào thì việc validate sẽ khó khăn hơn.


Lúc này chúng ta sẽ sử dụng useState() để quản lý giá trị và lỗi của nhiều nhóm input này.


Đi vào bài toán thực tế sau để hiểu rõ hơn: Thêm ca làm việc cho công ty, người dùng sẽ thực hiện thêm thủ công là trong ngày sẽ có bao nhiêu ca, mỗi ca sẽ có các input là: tên ca, thời gian bắt đầu ca, thời gian kết thúc ca và số lượng nhân viên cần có cho ca làm việc.


Đầu tiên, tạo danh sách ca làm việc và hiển thị lỗi cho từng input trong ca nếu trống:


export default function XepCa({ }) {
const [shifts, setShifts] = useState([]);
const [shiftsErrors, setShiftsErrors] = useState({});


return (
<div>
<div>
<ul>
{
shifts.map((item, index) => {
return (
<li key={index}>
<div>
<input name="shiftsName" value={item.shiftsName} onChange={(event) => shiftsInputChange(index, event)} />
{shiftsErrors[index]?.shiftsName && <span className='text-danger'>{shiftsErrors[index].shiftsName}</span>}
</div>
<div>
<input type='time' name="fromTime" value={item.fromTime} onChange={(event) => shiftsInputChange(index, event)} />
{shiftsErrors[index]?.fromTime && <span className='text-danger'>{shiftsErrors[index].fromTime}</span>}
</div>
<div>
<input type='time' name="toTime" value={item.toTime} onChange={(event) => shiftsInputChange(index, event)} />
{shiftsErrors[index]?.toTime && <span className='text-danger'>{shiftsErrors[index].toTime}</span>}
</div>
<div>
<input name="numberStaff" value={item.numberStaff} onChange={(event) => shiftsInputChange(index, event)} />
{shiftsErrors[index]?.numberStaff && <span className='text-danger'>{shiftsErrors[index].numberStaff}</span>}
</div>
</li>
)
})
}
</ul>
<button onClick={() => setShifts([...shifts, {}])}>Thêm ca</button>
</div>
<button onClick={handleSubmit}>Lưu thay đổi</button>
</div>
)
}


Cài đặt giá trị cho từng input khi change input đó:


export default function XepCa({ }) {

const shiftsInputChange = (index, event) => {
const { name, value } = event.target;
const newItems = [...shifts];
newItems[index][name] = value;
setShifts(newItems);
};


return (
)
}


Bắt lỗi input trống trong từng ca làm việc:


export default function XepCa({ }) {


const validateShifts = () => {
const newErrors = {};
shifts.forEach((item, index) => {
const itemErrors = {};
if (!item.shiftsName) itemErrors.shiftsName = 'Tên ca là bắt buộc!';
if (!item.fromTime) itemErrors.fromTime = 'Thời gian bắt đầu là bắt buộc!';
if (!item.toTime) itemErrors.toTime = 'Thời gian kết thúc là bắt buộc!';
if (!item.numberStaff) itemErrors.numberStaff = 'Sô lượng nhân viên là bắt buộc!';
if (Object.keys(itemErrors).length > 0) newErrors[index] = itemErrors;
});
setShiftsErrors(newErrors);
return Object.keys(newErrors).length;
};


return (
)
}



Thực hiện gửi form nếu không còn input nào trống, nếu có input trống thì show lỗi lên


export default function XepCa({ }) {


const handleSubmit = async () => {
if (validateShifts()) {
console.log('lỗi thêm ca')
return
}


console.log('thực hiện thêm ca')
// call api để thêm mới
}


return (
)
}


Vậy là xong việc validate nhóm input, nếu có những input đơn ngoài nhóm này thì cần kết hợp với Formik để xử lý nhanh hơn.

Liên hệ ngay tại đây với chúng tôi để được tư vấn nhanh nhất hoặc liên hệ:

Hotline: 0705.550.553

Email: bqsoftvn@gmail.com

Fanpage: https://www.facebook.com/bqsoftvn


Hân hạnh được hợp tác!

icon zalo
icon-mess