Files
Todo/components/ListForm.tsx
Paul Bailey 796bde22e7 feat: Add comprehensive input validation
- Created lib/validation.ts with validation utilities for all form inputs
- Added validation for list titles, item titles, colors, dates, tags, descriptions, and notes
- Implemented inline validation with real-time error feedback in ListForm
- Enhanced ItemForm with comprehensive validation for all fields
- Updated InlineItemCreate with validation
- Added input sanitization to prevent XSS attacks
- Updated server actions to use validation utilities
- Added maxLength attributes to prevent excessive input
- Improved accessibility with aria-invalid and aria-describedby attributes
- Added visual feedback for validation errors with red borders
- Validates Requirements 1.1 and 2.1
2025-12-01 21:26:26 +00:00

169 lines
5.2 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import { createList, updateList } from '@/lib/actions'
import { useRouter } from 'next/navigation'
import { useToast } from './ToastContainer'
import { validateListTitle } from '@/lib/validation'
interface ListFormProps {
list?: {
id: string
title: string
color: string
}
onCancel?: () => void
onSuccess?: () => void
}
const PRESET_COLORS = [
'#3B82F6', // blue
'#EF4444', // red
'#10B981', // green
'#F59E0B', // amber
'#8B5CF6', // purple
'#EC4899', // pink
'#06B6D4', // cyan
'#F97316', // orange
]
export default function ListForm({ list, onCancel, onSuccess }: ListFormProps) {
const router = useRouter()
const { showToast } = useToast()
const [title, setTitle] = useState(list?.title || '')
const [color, setColor] = useState(list?.color || PRESET_COLORS[0])
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState('')
const [touched, setTouched] = useState(false)
// Inline validation when title changes
useEffect(() => {
if (touched) {
const result = validateListTitle(title)
setError(result.isValid ? '' : result.error || '')
}
}, [title, touched])
const handleTitleBlur = () => {
setTouched(true)
const result = validateListTitle(title)
setError(result.isValid ? '' : result.error || '')
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Validate before submission
const result = validateListTitle(title)
if (!result.isValid) {
setError(result.error || 'Invalid input')
setTouched(true)
return
}
setIsSubmitting(true)
setError('')
try {
if (list) {
// Update existing list
await updateList(list.id, { title: title.trim(), color })
showToast('List updated successfully', 'success')
} else {
// Create new list
await createList(title.trim(), color)
showToast('List created successfully', 'success')
}
if (onSuccess) {
onSuccess()
} else {
router.refresh()
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to save list. Please try again.'
setError(errorMessage)
showToast(errorMessage, 'error')
console.error(err)
} finally {
setIsSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
<div>
<label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-2">
List Title *
</label>
<input
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
onBlur={handleTitleBlur}
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
error && touched
? 'border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:ring-blue-500'
}`}
placeholder="Enter list title"
disabled={isSubmitting}
autoFocus
maxLength={200}
aria-invalid={error && touched ? 'true' : 'false'}
aria-describedby={error && touched ? 'title-error' : undefined}
/>
{error && touched && (
<p id="title-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
{error}
</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2 sm:mb-3">
Color
</label>
<div className="flex gap-2 sm:gap-3 flex-wrap">
{PRESET_COLORS.map((presetColor) => (
<button
key={presetColor}
type="button"
onClick={() => setColor(presetColor)}
className={`w-11 h-11 sm:w-12 sm:h-12 rounded-lg transition-all tap-target-sm ${
color === presetColor
? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
: 'hover:scale-105 active:scale-95'
}`}
style={{ backgroundColor: presetColor }}
disabled={isSubmitting}
aria-label={`Select color ${presetColor}`}
/>
))}
</div>
</div>
<div className="flex flex-col-reverse sm:flex-row gap-2 sm:gap-3 justify-end pt-2">
{onCancel && (
<button
type="button"
onClick={onCancel}
disabled={isSubmitting}
className="w-full sm:w-auto px-4 sm:px-5 py-3 text-gray-700 bg-gray-100 hover:bg-gray-200 active:bg-gray-300 rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
>
Cancel
</button>
)}
<button
type="submit"
disabled={isSubmitting}
className="w-full sm:w-auto px-4 sm:px-5 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
>
{isSubmitting ? 'Saving...' : list ? 'Update List' : 'Create List'}
</button>
</div>
</form>
)
}