React - form

by oktaviardi pratama

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.7/cjs/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.7/cjs/react-dom.production.min.js"></script>
<!-- Load React and ReactDOM from CDN -->
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>

<!-- The root element where your React app will mount -->
<div id="app"></div>

React

const { useState } = React;

function Checkout() {
  const [form, setForm] = useState({
    name: "",
    email: "",
    address: "",
  });
  //form.name = "khansa"
  //flow#1 setForm({name: "khansa", email: "", address: ""})
  //flow#2 setForm({name: "", email: "[email protected]", address: ""})
  //flow#3 setForm({name: "", email: "", address: "asda asd asdaswd"})
  // // setForm(...form, ...{name:"khansa"})
  // {
  //   name: "khansa",
  //   email: "",
  //   address: "",
  // }
  // setForm(...form, ...{email:"[email protected]"})
  // {
  //   name: "khansa",
  //   email: "[email protected]",
  //   address: "",
  // }
    // setForm(...form, ...{city:"jakarta"})
  // {
  //   name: "khansa",
  //   email: "[email protected]",
  //   address: "",
  //   city: "jakarta",
  // }

  // Default error states initialized as empty strings
  const [errors, setErrors] = useState({
    name: "",
    email: "",
    address: "",
  });

  const validateField = (name, value) => {
    if (!value.trim()) {
      return `${name.charAt(0).toUpperCase() + name.slice(1)} is required.`;
    }
    
    if (name === "name") {
      if (value.length > 32) {
        return "Name cannot be more than 32 characters.";
      }
      // Letters and spaces only
      if (!/^[a-zA-Z\s]+$/.test(value)) {
        return "Name must contain letters and spaces only (no numbers).";
      }
    }

    if (name === "email") {
      if (!/\S+@\S+\.\S+/.test(value)) {
        return "Invalid email format.";
      }
    }

    if (name === "address") {
      // Updated RegEx: Allows alphanumeric characters, spaces, and , . - / _ |
      // Special characters inside the bracket are escaped where necessary (\-, \/)
      if (!/^[a-zA-Z0-9\s,.\-/_|]+$/.test(value)) {
        return "Address contains unpermitted special characters. Only format symbols like , . - / _ | are allowed.";
      }
    }

    return ""; // Clear error if...