r/reactjs • • 1d ago
Show /r/reactjs How do you validate phone, card and postcode fields in React Hook Form? I built a small library for it and would like feedback
For most forms I end up copying the same phone regex, a Luhn check for card numbers and a postcode pattern into every project. So I put them into a small zero-dependency library, snap-validate. It implements Standard Schema, so it works with React Hook Form's standardSchemaResolver with no adapter:
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
import { validators, toStandardSchema } from 'snap-validate';
const signupSchema = toStandardSchema({
email: validators.email,
phone: (value) => validators.phone(value, 'international'),
password: validators.password
});
export function SignupForm() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm({ resolver: standardSchemaResolver(signupSchema) });
return (
<form onSubmit={handleSubmit((data) => console.log(data))} noValidate>
<input type="email" {...register('email')} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<input type="tel" {...register('phone')} />
{errors.phone && <p role="alert">{errors.phone.message}</p>}
<input type="password" {...register('password')} />
{errors.password && <p role="alert">{errors.password.message}</p>}
<button type="submit">Create account</button>
</form>
);
}
What it does:
- Each field gets its own message, such as "Invalid phone number format"
- Valid data comes back cleaned: the email is trimmed and lowercased
- It also works with TanStack Form. One thing I learned there: schema errors are objects, so
errors.join(', ')prints[object Object]. Map to.messagefirst.
It's not trying to replace Zod. It's the format checks I kept rewriting, in about 4 kB.
Two questions for you:
- Which field formats do you end up writing by hand? I'm deciding which postcode countries and phone formats to add next.
- Do you prefer presets like
validators.phone(), or building everything from a general schema library?
I'll put the playground and the full write-up in a comment. It's MIT-licensed, and new contributors are welcome.
1
Upvotes