How do I validate and format Haitian phone numbers (+509)?

posée 4 months ago303 vuesen

7

My signup form accepts Haitian phone numbers. Users type them in many ways: 3712-3456, 509 37 12 34 56, +50937123456. How do I validate and store them consistently?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

1 réponse

5
✓
✓ Réponse acceptée

Haitian numbers are 8 digits after the country code +509. Normalize everything to E.164 (+50937123456) for storage, and format only for display.

Use libphonenumber-js. Numbering plans change over time, and the library tracks them for you:

import { parsePhoneNumberFromString } from 'libphonenumber-js';

export function normalizeHtPhone(input: string): string | null {
  const p = parsePhoneNumberFromString(input, 'HT'); // default country for numbers typed without +509
  if (!p || !p.isValid()) return null;
  return p.number;            // '+50937123456' (E.164), store this
}

// display: p.formatInternational() → '+509 3712 3456'

Tips: - Default the country to HT, but accept international numbers too. Many users are in the diaspora (US, Canada, France, Dominican Republic, Chile…). - Store E.164 in the database with a unique index if the phone is used for login. - If you send OTP by SMS, verify the number before trusting it, and rate-limit sends: SMS costs money and is a target for abuse.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.