validate timelog-form's time and description fields

Set states to keep track of whether or not the specific fields have
errors, and what error message they should display.

Add separate validation function that is checked upon submitting the
form.

Add appropriate properties for the time and description fields to
adjust their behavior avvording to possible errors.
This commit is contained in:
regularmute
2024-03-19 15:29:05 +02:00
parent 5f86865cbf
commit 0799ed54f3
@@ -7,6 +7,10 @@ export const TimeLogForm = ({ handleSubmit, disabled }) => {
const [date, setDate] = useState(new Date().toISOString().slice(0, 10))
const [time, setTime] = useState('')
const [description, setDescription] = useState('')
const [formTimeHasError, setFormTimeHasError] = useState(false)
const [timeErrorMessage, setTimeErrorMessage] = useState('')
const [formDescriptionHasError, setFormDescriptionHasError] = useState(false)
const [descriptionErrorMessage, setDescriptionErrorMessage] = useState('')
const handleDateChange = (event) => {
setDate(event.target.value)
@@ -20,10 +24,34 @@ export const TimeLogForm = ({ handleSubmit, disabled }) => {
setDescription(event.target.value)
}
const formIsInvalid = () => {
let error_exists = false
const timePattern = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/
if (!timePattern.test(time)) {
setFormTimeHasError(true)
setTimeErrorMessage('Time must be in format HH:MM')
error_exists = true
}
if (description.length < 5) {
setFormDescriptionHasError(true)
setDescriptionErrorMessage('Description must be at least 5 characters')
error_exists = true
}
return error_exists
}
const handleFormSubmit = (event) => {
event.preventDefault()
handleSubmit(date, time, description)
clearForm()
if (formIsInvalid()) {
return
} else {
setFormTimeHasError(false)
setTimeErrorMessage('')
setFormDescriptionHasError(false)
setDescriptionErrorMessage('')
handleSubmit(date, time, description)
clearForm()
}
}
const clearForm = () => {
@@ -51,6 +79,8 @@ export const TimeLogForm = ({ handleSubmit, disabled }) => {
/>
<TextField
disabled={disabled}
error={formTimeHasError}
helperText={formTimeHasError && timeErrorMessage}
className="time"
id="time"
label="Time (HH:MM)"
@@ -64,6 +94,8 @@ export const TimeLogForm = ({ handleSubmit, disabled }) => {
/>
<TextField
disabled={disabled}
error={formDescriptionHasError}
helperText={formDescriptionHasError && descriptionErrorMessage}
className="description"
id="description"
label="Description"