form-test

mail@pastecode.io avatar
unknown
jsx
a year ago
2.8 kB
1
Indexable
Never
import { useState } from 'react';

function MyForm() {
  const [formInputs, setFormInputs] = useState([
    { name: 'email', value: '', error: '' },
    { name: 'password', value: '', error: '' },
  ]);

  // handle form input changes
  const handleInputChange = (event, index) => {
    const { name, value } = event.target;
    setFormInputs((prevState) => {
      const updatedInputs = [...prevState];
      updatedInputs[index] = { ...updatedInputs[index], value };
      return updatedInputs;
    });
  };

  // handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();
    // validate form inputs
    const errors = {};
    formInputs.forEach((input, index) => {
      if (input.value.trim() === '') {
        errors[input.name] = `${input.name} is required`;
        setFormInputs((prevState) => {
          const updatedInputs = [...prevState];
          updatedInputs[index] = {
            ...updatedInputs[index],
            error: `${input.name} is required`,
          };
          return updatedInputs;
        });
      } else if (input.name === 'email' && !/\S+@\S+\.\S+/.test(input.value)) {
        errors[input.name] = `Invalid email address`;
        setFormInputs((prevState) => {
          const updatedInputs = [...prevState];
          updatedInputs[index] = {
            ...updatedInputs[index],
            error: `Invalid email address`,
          };
          return updatedInputs;
        });
      } else if (input.name === 'password' && input.value.length < 8) {
        errors[input.name] = `Password must be at least 8 characters long`;
        setFormInputs((prevState) => {
          const updatedInputs = [...prevState];
          updatedInputs[index] = {
            ...updatedInputs[index],
            error: `Password must be at least 8 characters long`,
          };
          return updatedInputs;
        });
      } else {
        setFormInputs((prevState) => {
          const updatedInputs = [...prevState];
          updatedInputs[index] = { ...updatedInputs[index], error: '' };
          return updatedInputs;
        });
      }
    });
    // submit form if no errors
    if (Object.keys(errors).length === 0) {
      // submit form
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {formInputs.map((input, index) => (
        <div key={input.name}>
          <label htmlFor={input.name}>{input.name}</label>
          <input
            type={input.name === 'password' ? 'password' : 'text'}
            id={input.name}
            name={input.name}
            value={input.value}
            onChange={(event) => handleInputChange(event, index)}
          />
          {input.error && <div className="error">{input.error}</div>}
        </div>
      ))}
      <button type="submit">Submit</button>
    </form>
  );
}