To capture user input and perform form validation in React, we can utilize the built-in form handling capabilities and validation logic.
When a user interacts with a form, we can listen to the onSubmit
event and execute a function to handle the form submission.
Here's an example of how we can handle form submission and perform basic validation:
1// Example form validation
2const validateForm = () => {
3 // Get form values
4 const name = document.getElementById('name').value;
5 const email = document.getElementById('email').value;
6 const password = document.getElementById('password').value;
7
8 // Perform validation
9 if (!name || !email || !password) {
10 console.log('Please fill in all fields');
11 return;
12 }
13
14 if (password.length < 6) {
15 console.log('Password must be at least 6 characters long');
16 return;
17 }
18
19 console.log('Form submitted successfully');
20};
21
22// Handle form submission
23const form = document.getElementById('form');
24form.addEventListener('submit', (e) => {
25 e.preventDefault();
26 validateForm();
27});
In the code snippet above, we define a function validateForm()
that retrieves the values from the form inputs and performs the validation checks. If any field is empty or the password is less than 6 characters long, an error message is logged to the console.
We add an event listener to the form's submit
event and prevent the default form submission behavior using e.preventDefault()
. Instead, we call the validateForm()
function to handle the form submission and perform the necessary validation.
This is a basic example, but in a real-world scenario, you would typically use a form library like React Hook Form
or Formik
to handle more complex form validation and management.
Next, we will explore implementing authentication in our payment app.
xxxxxxxxxx
// Example form validation
const validateForm = () => {
// Get form values
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// Perform validation
if (!name || !email || !password) {
console.log('Please fill in all fields');
return;
}
if (password.length < 6) {
console.log('Password must be at least 6 characters long');
return;
}
console.log('Form submitted successfully');
};
// Handle form submission
const form = document.getElementById('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
validateForm();
});