Advertisement
fabiobiondi

React Pro - Real World App - Ch6. 13. Regex Validators

Mar 18th, 2023
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import clsx from 'clsx';
  2. import { selectTotalCartCost, useCart } from '@/services/cart';
  3. import { ChangeEvent, useState } from 'react';
  4.  
  5. export const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  6.  
  7. export function CheckoutPage() {
  8.   const [user, setUser] = useState({ name: '', email: ''});
  9.   const [dirty, setDirty] = useState(false);
  10.  
  11.   const totalCartCost = useCart(selectTotalCartCost);
  12.  
  13.   function changeHandler(e: ChangeEvent<HTMLInputElement>) {
  14.     const name = e.currentTarget.name;
  15.     const value = e.currentTarget.value;
  16.     setUser(state => ({ ...state, [name]: value }));
  17.     setDirty(true);
  18.   }
  19.  
  20.   const isNameValid = user.name.length;
  21.   const isEmailValid = user.email.match(EMAIL_REGEX);
  22.   const isValid = isNameValid && isEmailValid;
  23.  
  24.   return (
  25.     <div className="max-w-sm mx-auto">
  26.       <h1 className="title">CHECKOUT</h1>
  27.  
  28.       <div className="text-xl my-3 border-b">{totalCartCost}</div>
  29.  
  30.       <form className="flex flex-col gap-3">
  31.         Your name:
  32.         <input
  33.           type="text" placeholder="your name"
  34.           name="name"
  35.           value={user.name}
  36.           onChange={changeHandler}
  37.           className={clsx({ 'error': !isNameValid && dirty})}
  38.         />
  39.  
  40.         Your email
  41.         <input
  42.           type="email" placeholder="Your email"
  43.           name="email"
  44.           value={user.email}
  45.           onChange={changeHandler}
  46.           className={clsx({ 'error': !isEmailValid && dirty })}
  47.         />
  48.  
  49.         <button className="btn primary" disabled={!isValid}>
  50.           CONFIRM ORDER
  51.         </button>
  52.       </form>
  53.  
  54.       <pre>{JSON.stringify(user, null, 2)}</pre>
  55.     </div>
  56.   )
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement