How to validate an NPI number in JavaScript
Client-side validation should only enforce shape: ten digits, no spaces. That catches typos before you spend a lookup credit or hit the registry.
Authoritative validation is whether the NPI exists and is active in NPPES today. A small backend call (or your own API route) should perform that lookup and return a normalized provider object your UI can render.
Use a stable HTTP contract—Bearer auth, documented 404 for npi_not_found, and JSON fields for entity type and taxonomy—so enrollment and roster screens do not fork parsers per feature.
Format check + registry lookup
const NPI_PATTERN = /^\d{10}$/;
export function isValidNpiFormat(npi) {
return NPI_PATTERN.test(npi);
}
export async function lookupNpi(npi, apiKey) {
if (!isValidNpiFormat(npi)) {
throw new Error("NPI must be exactly 10 digits");
}
const res = await fetch(`https://healthproviderapi.com/api/v1/npi/${npi}`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
if (res.status === 404) return { found: false };
if (!res.ok) throw new Error(`Lookup failed: ${res.status}`);
const json = await res.json();
return { found: true, provider: json.data };
}