I'll create a phone number input field with robust validation using React Hook Form, Zod, and shadcn/ui components. This implementation will handle various phone number formats and provide clear feedback to users.
This phone number validation implementation provides a comprehensive approach that:
Visual Feedback:
/api/validate-phone/route.ts
) that can be used for additional validation before saving to a database.You can easily integrate this with a Server Action for form submission 1:
"use server"
import { validatePhoneNumber } from "@/lib/phone-validation"
export async function savePhoneNumber(formData: FormData) {
const country = formData.get("country") as string
const phoneNumber = formData.get("phoneNumber") as string
// Validate on the server
const validationResult = await validatePhoneNumber(country, phoneNumber)
if (!validationResult.valid) {
return {
success: false,
errors: validationResult.errors
}
}
// Save to database or perform other actions
// ...
return {
success: true,
data: {
country,
phoneNumber: validationResult.normalizedNumber
}
}
}
Let me fix that regular expression error and create a proper phone number field with comprehensive validation.
The error was in the regular expression pattern. Instead of using a complex regex with problematic $
characters, I've implemented a more robust approach:
I'm using a combination of:
Multiple Format Support: Handles various input formats:
Validation Rules:
User Experience:
This implementation uses React Hook Form with Zod validation and shadcn/ui components as requested, providing a clean, accessible phone number input with comprehensive validation.