All files / app/components/registerForm RegisterForm.js

100% Statements 43/43
100% Branches 60/60
100% Functions 11/11
100% Lines 42/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190                                                96x 96x 96x 96x 96x 96x   96x 96x 96x     5x 1x 1x   4x 4x 4x     96x 96x 96x 96x 96x 96x     96x           6x               6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     96x               10x                     10x                     9x                     9x                     9x                   9x                                                               4x                              
import {useState} from "react";
import  "../../utils/module";
import {isAdult, isValidCodePost, isValidEmail, isValidName} from "../../utils/module";
 
/**
 * Formulaire d'inscription utilisateur.
 *
 * Champs : prénom, nom, email, date de naissance, code postal, ville.
 * - Affiche un message d'erreur en rouge sous chaque champ invalide.
 * - Le bouton "Send" est désactivé tant que les champs ne sont pas tous valides.
 * - À la soumission : enregistre l'utilisateur dans `localStorage` (clé `users`),
 *   affiche un toaster de succès et vide le formulaire.
 *
 * Règles de validation (voir `utils/module.js`) :
 * - prénom, nom, ville : lettres, accents, trémas, tirets, apostrophes, espaces.
 * - email : format `local@domaine.ext`.
 * - code postal : 5 chiffres (format français).
 * - date de naissance : majorité requise (>= 18 ans).
 *
 * @component
 * @returns {JSX.Element} Le formulaire d'inscription.
 */
export default function RegisterForm() {
 
    const [firstname, setFirstname] = useState("")
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [birth, setBirth] = useState("");
    const [postcode, setPostcode] = useState("");
    const [city, setCity] = useState("");
 
    const [showData, setShowData] = useState(false);
    const [users, setUsers] = useState([]);
    const [toast, setToast] = useState("");
 
    function toggleGetData() {
        if (showData) {
            setShowData(false);
            return;
        }
        const list = JSON.parse(localStorage.getItem("users")) || [];
        setUsers(list);
        setShowData(true);
    }
 
    const firstnameError = firstname && !isValidName(firstname) ? "Invalid firstname" : "";
    const nameError = name && !isValidName(name) ? "Invalid name" : "";
    const emailError = email && !isValidEmail(email) ? "Invalid email" : "";
    const postCodeError = postcode && !isValidCodePost(postcode) ? "Invalid postcode" : "";
    const cityError = city && !isValidName(city) ? "Invalid city" : "";
    const birthError = birth && !isAdult(new Date(birth)) ? "You are too young" : "";
 
    const isFormValid =
        firstname && name && email && birth && postcode && city &&
        isValidName(firstname) && isValidName(name) && isValidName(city) &&
        isValidEmail(email) && isValidCodePost(postcode) &&
        isAdult(new Date(birth));
 
    function handleSubmission() {
        let userData = {
            FirstName: firstname,
            Name: name,
            Email: email,
            Birth: birth,
            Postcode: postcode,
            City: city,
        };
        const list = JSON.parse(localStorage.getItem('users')) || [];
        list.push(userData);
        localStorage.setItem('users', JSON.stringify(list));
        setToast("Saved Successfully");
        setTimeout(() => setToast(""), 3000);
        setFirstname("");
        setName("");
        setEmail("");
        setBirth("");
        setPostcode("");
        setCity("");
    }
 
    return(
        <div>
            <label htmlFor="firstname">First Name </label>
            <input
                id="firstname"
                type="text"
                name="first name"
                placeholder="Type your first name"
                onChange={(e) => setFirstname(e.target.value)}
                value={firstname}
            />
            {firstnameError && <span style={{color: 'red'}}>{firstnameError}</span>}
 
            <label htmlFor="name"> Name </label>
            <input
                id="name"
                type="text"
                name="name"
                placeholder="Type your name"
                onChange={(e) => setName(e.target.value)}
                value={name}
            />
            {nameError && <span style={{color: 'red'}}>{nameError}</span>}
 
            <label htmlFor="email"> Email </label>
            <input
                id="email"
                type="email"
                name="email"
                placeholder="Type your email"
                onChange={(e) => setEmail(e.target.value)}
                value={email}
            />
            {emailError && <span style={{color: 'red'}}>{emailError}</span>}
 
            <label htmlFor="birth"> birth </label>
            <input
                id="birth"
                type="date"
                name="birth"
                placeholder="Type your birth"
                onChange={(e) => setBirth(e.target.value)}
                value={birth}
            />
            {birthError && <span style={{color: 'red'}}>{birthError}</span>}
 
            <label htmlFor="postcode"> postcode </label>
            <input
                id="postcode"
                type="text"
                name="postcode"
                placeholder="Type your postcode"
                onChange={(e) => setPostcode(e.target.value)}
                value={postcode}/>
            {postCodeError && <span style={{color: 'red'}}>{postCodeError}</span>}
 
            <label htmlFor="city"> city </label>
            <input
                id="city"
                type="text"
                name="city"
                placeholder="Type your city"
                onChange={(e) => setCity(e.target.value)}
                value={city}/>
            {cityError && <span style={{color: 'red'}}>{cityError}</span>}
 
            <button onClick={handleSubmission} disabled={!isFormValid}>Send</button>
 
            <button onClick={toggleGetData}>Show registered users</button>
 
            {toast && (
                <div
                    role="alert"
                    data-testid="toast"
                    style={{
                        position: 'fixed',
                        bottom: 20,
                        right: 20,
                        background: '#16a34a',
                        color: 'white',
                        padding: '10px 16px',
                        borderRadius: 4,
                    }}
                >
                    {toast}
                </div>
            )}
 
            {showData && (
                <div className="data" data-testid="users-list">
                    {users.length === 0 ? (
                        <div>No registered users</div>
                    ) : (
                        users.map((u, i) => (
                            <div key={i} className="user-item">
                                <div>First Name - {u.FirstName}</div>
                                <div>Name - {u.Name}</div>
                                <div>Email - {u.Email}</div>
                                <div>Birth - {u.Birth}</div>
                                <div>Postcode - {u.Postcode}</div>
                                <div>City - {u.City}</div>
                            </div>
                        ))
                    )}
                </div>
            )}
        </div>)
 
}