From 4113ce56ad1a9aa790c7fac97af05418dd776e9d Mon Sep 17 00:00:00 2001 From: powermaker450 Date: Tue, 10 Sep 2024 16:41:34 -0400 Subject: [PATCH] Client-side input validation --- src/pages/Home.tsx | 54 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index ab2b9e6..57fd18b 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -1,4 +1,4 @@ -import { Alert, Grow, Rating, Typography } from "@mui/material"; +import { Alert, Button, Dialog, DialogActions, DialogContent, Grow, Rating, Typography } from "@mui/material"; import "../App.css"; import ButtonRow, { ActionProps } from "../components/ButtonRow"; import ReviewField, { ReviewFieldProps } from "../components/ReviewField"; @@ -7,6 +7,7 @@ import EndpointDialog from "../components/EndpointDialong"; function Home() { const [rating, setNewRating] = useState(0); + const [modal, showModal] = useState(false); const [showAlert, changeAlert] = useState(false); const [alertText, changeAlertText] = useState(""); const [secure, setSecure] = useState(false); @@ -47,7 +48,22 @@ function Home() { setNewRating(null); }; - const showThenHide = async () => { + const handleSubmit = async () => { + if (!endpoint) { + showModal(true); + return; + } + + if (!rating) { + showModal(true); + return; + } + + if (fields[0].dynamicState[0].length < 2) { + showModal(true); + return; + } + await fetch(endpoint ? `${secure ? "https" : "http"}://${endpoint}/post` : "http://localhost:8080/post", { method: "POST", body: JSON.stringify({ @@ -88,6 +104,18 @@ function Home() { }); }; + const getEmptyFields = () => { + return ( + !rating + ? "You must enter a rating!" + : fields[0].dynamicState[0].length < 2 + ? "You must enter a username at least 2 characters long!" + : !endpoint + ? "Endpoint is not set!" + : "" + ); + } + const buttons: ActionProps[] = [ { name: "Clear", @@ -97,7 +125,7 @@ function Home() { { name: "Submit", type: "contained", - action: showThenHide, + action: handleSubmit, }, ]; @@ -148,6 +176,26 @@ function Home() { {info} + + showModal(false)} + > + + + {getEmptyFields()} + + + + + + + );