BCSL657B Program 6

6. Design and implement a React Form that collects user input for name, email, and password. Form Fields are Name, Email, Password. Ensure all fields are filled before allowing form submission. Validate the email field to ensure it follows the correct email format (e.g., example@domain.com). Optionally enforce a minimum password length or complexity. Display error messages for invalid or missing inputs. Provide visual cues (e.g., red borders) to highlight invalid fields. Prevent form submission until all fields pass validation. Log or display the entered data upon successful submission (optional). Add a “Show Password” toggle for the password field. Implement client-side sanitization to ensure clean input.

Step 1: Create a New React Application
First, you need to create a new React app using below command. Open your terminal and run:

npx create-react-app react-form

This will set up a new React project in a folder called react-form. After the installation is complete, navigate to the project directory:

cd react-form

Step 2: Set Up the Folder Structure
Create the folder structure. Here’s how you can organize the directories:

  1. Inside the src folder:
    • Create a components folder.
    • Inside components, create Form.js file

Form.js:

import React, { useState, useEffect, useCallback } from 'react';

const Form = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
  });

  const [errors, setErrors] = useState({
    name: '',
    email: '',
    password: '',
  });

  const [showPassword, setShowPassword] = useState(false);
  const [isFormValid, setIsFormValid] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value.trim(),
    }));
  };

  const validateForm = useCallback(() => {
    let isValid = true;
    const newErrors = { name: '', email: '', password: '' };

    if (!formData.name) {
      newErrors.name = 'Name is required.';
      isValid = false;
    }

    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!formData.email || !emailPattern.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address.';
      isValid = false;
    }

    if (!formData.password) {
      newErrors.password = 'Password is required.';
      isValid = false;
    } else if (formData.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters long.';
      isValid = false;
    }

    setErrors(newErrors);
    setIsFormValid(isValid);
  }, [formData]);

  useEffect(() => {
    validateForm();
  }, [formData, validateForm]);

  const handleSubmit = (e) => {
    e.preventDefault();

    if (isFormValid) {
      console.log('Form Data:', formData);
      setFormData({
        name: '',
        email: '',
        password: '',
      });
    }
  };

  return (
    <div className="form-container">
      <h2 className="form-title">Registration Form</h2>
      <form onSubmit={handleSubmit} className="form">
        <div className="form-group">
          <label htmlFor="name" className="form-label">Name</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            className={`form-input ${errors.name ? 'error' : ''}`}
            placeholder="Enter your name"
          />
          {errors.name && <div className="error-message">{errors.name}</div>}
        </div>

        <div className="form-group">
          <label htmlFor="email" className="form-label">Email</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            className={`form-input ${errors.email ? 'error' : ''}`}
            placeholder="Enter your email"
          />
          {errors.email && <div className="error-message">{errors.email}</div>}
        </div>

        <div className="form-group">
          <label htmlFor="password" className="form-label">Password</label>
          <input
            type={showPassword ? 'text' : 'password'}
            id="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            className={`form-input ${errors.password ? 'error' : ''}`}
            placeholder="Enter your password"
          />
          {errors.password && <div className="error-message">{errors.password}</div>}
        </div>

        <div className="form-group password-toggle">
          <label>
            <input
              type="checkbox"
              checked={showPassword}
              onChange={() => setShowPassword(!showPassword)}
            />
            Show Password
          </label>
        </div>

        <div className="form-group">
          <button type="submit" className="form-submit" disabled={!isFormValid}>
            Submit
          </button>
        </div>
      </form>
    </div>
  );
};

export default Form;

Step 3. App Component(src/App.js):
In your src/App.js, import the Form component and use it or copy the below code and paste it into the App.js file.

import React from 'react';
import './App.css';
import Form from './components/Form';

function App() {
  return (
    <div className="App">
      <Form />
    </div>
  );
}

export default App;

Step 4: Add Some Basic Styles(src/App.css)
Add some styles in src/App.css to make the layout nicer. Copy the below code and paste it into the App.css file.

.form-container {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f7f7;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  font-size: 14px;
  font-weight: 600;
  color: #555;
}

.form-input {
  width: 100%;
  padding: 12px;
  margin-top: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-input.error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

.password-toggle {
  margin-bottom: 20px;
}

.form-submit {
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.form-submit:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.form-submit:hover:not(:disabled) {
  background-color: #45a049;
}

Step 5: Run the application
Back in your terminal, start the development server by running:

npm start

OUTPUT:

BCSL657B Program 6 Output 1
BCSL657B Program 6 Output 2

“Fixing the Module not found: Error: Can't resolve 'web-vitals' Error in React”

Error

Option 1: Install the web-vitals package
If you want to keep the performance monitoring functionality and resolve the error, simply install the web-vitals package.

  1. In the terminal, navigate to your project folder (if not already there):
cd react-form
  1. Install web-vitals by running the following command:
npm install web-vitals
  1. After installation is complete, restart the development server:
npm start

This should resolve the error, and your application should compile correctly.

Option 2: Remove the Web Vitals Code (If Not Needed)
If you don’t need performance monitoring and want to get rid of the error, you can safely remove the import and usage of web-vitals from your code.

  1. Open src/reportWebVitals.js and remove its contents or just comment out the code:
// import { reportWebVitals } from './reportWebVitals';

// You can safely remove the call to reportWebVitals or leave it commented out
// reportWebVitals();
  1. Save the file, and the application should compile without the error. You can now continue developing your app.
guest
2 Comments
Inline Feedbacks
View all comments
React Dev
React Dev
09-05-2025 9:37 AM

Module not found: Error: Can’t resolve ‘./Form.css’. Provide Code for Form.css, it is missing.

***************************Solution*****************************
Comment Out the Import Statement of Form.css in Form.js

// import ‘./Form.css’;

Last edited 1 month ago by React Dev
2
0
Would love your thoughts, please comment.x
()
x