Client-side input validation

This commit is contained in:
powermaker450 2024-09-10 16:41:34 -04:00
parent 0d6f7e3e8d
commit 4113ce56ad

View file

@ -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 "../App.css";
import ButtonRow, { ActionProps } from "../components/ButtonRow"; import ButtonRow, { ActionProps } from "../components/ButtonRow";
import ReviewField, { ReviewFieldProps } from "../components/ReviewField"; import ReviewField, { ReviewFieldProps } from "../components/ReviewField";
@ -7,6 +7,7 @@ import EndpointDialog from "../components/EndpointDialong";
function Home() { function Home() {
const [rating, setNewRating] = useState<number | null>(0); const [rating, setNewRating] = useState<number | null>(0);
const [modal, showModal] = useState(false);
const [showAlert, changeAlert] = useState(false); const [showAlert, changeAlert] = useState(false);
const [alertText, changeAlertText] = useState(""); const [alertText, changeAlertText] = useState("");
const [secure, setSecure] = useState(false); const [secure, setSecure] = useState(false);
@ -47,7 +48,22 @@ function Home() {
setNewRating(null); 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", { await fetch(endpoint ? `${secure ? "https" : "http"}://${endpoint}/post` : "http://localhost:8080/post", {
method: "POST", method: "POST",
body: JSON.stringify({ 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[] = [ const buttons: ActionProps[] = [
{ {
name: "Clear", name: "Clear",
@ -97,7 +125,7 @@ function Home() {
{ {
name: "Submit", name: "Submit",
type: "contained", type: "contained",
action: showThenHide, action: handleSubmit,
}, },
]; ];
@ -148,6 +176,26 @@ function Home() {
{info} {info}
</Grow> </Grow>
</div> </div>
<Dialog
open={modal}
onClose={() => showModal(false)}
>
<DialogContent>
<Typography variant="body1">
{getEmptyFields()}
</Typography>
</DialogContent>
<DialogActions>
<Button
variant="contained"
onClick={() => showModal(false)}
>
Ok
</Button>
</DialogActions>
</Dialog>
</div> </div>
</> </>
); );