Skip to content

Commit

Permalink
Add field validation to RestaurantForm
Browse files Browse the repository at this point in the history
In the RestaurantForm component, field validation has been added to the input fields "title" and "city" to prompt the user if either field is left empty. This implementation enhances user experience by providing immediate feedback and preventing form submission if the required fields are empty.
  • Loading branch information
josch87 committed Jun 4, 2024
1 parent b2fe0fc commit 8385023
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,10 @@ export const StyledFormRow = styled.div`
export const StyledInputField = styled.input`
border-radius: 4px;
padding: 2px 5px;
`;

export const StyledFieldError = styled.p`
color: red;
font-size: .9rem;
margin: 0 .3rem;
`;
22 changes: 21 additions & 1 deletion frontend/src/components/RestaurantForm/RestaurantForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,33 @@ import {ChangeEvent, FormEvent, useState} from "react";
import {NewRestaurantDTOType} from "../../model/Restaurant.ts";
import axios from "axios";
import {useNavigate} from "react-router-dom";
import {StyledForm, StyledFormBody, StyledFormRow, StyledInputField} from "./RestaurantForm.styled.ts";
import {
StyledFieldError,
StyledForm,
StyledFormBody,
StyledFormRow,
StyledInputField
} from "./RestaurantForm.styled.ts";

export default function RestaurantForm() {

const initialFieldValidation = {
title: "",
city: ""
}

const [formData, setFormData] = useState<NewRestaurantDTOType>({title: "", city: ""});
const [fieldValidation, setFieldValidation] = useState<NewRestaurantDTOType>(initialFieldValidation);
const navigate = useNavigate();

function handleUserInput(event: ChangeEvent<HTMLInputElement>) {
setFormData({...formData, [event.target.name]: event.target.value});

if (event.target.value.trim() === "") {
setFieldValidation({...fieldValidation, [event.target.name]: "Field is required"});
} else if (event.target.value.trim() !== "") {
setFieldValidation({...fieldValidation, [event.target.name]: ""});
}
}

function handleAddRestaurant(event: FormEvent<HTMLFormElement>) {
Expand All @@ -36,6 +54,7 @@ export default function RestaurantForm() {
value={formData.title}
required
/>
<StyledFieldError>{fieldValidation.title ? fieldValidation.title : undefined}</StyledFieldError>
</StyledFormRow>
<StyledFormRow>
<label htmlFor="city">City</label>
Expand All @@ -46,6 +65,7 @@ export default function RestaurantForm() {
value={formData.city}
required
/>
<StyledFieldError>{fieldValidation.city}</StyledFieldError>
</StyledFormRow>
</StyledFormBody>
<button type="submit">Add</button>
Expand Down

0 comments on commit 8385023

Please sign in to comment.