Last active
November 6, 2024 16:58
-
-
Save gitawego/ebd917c6f2eb7c5d57593512f9628ac5 to your computer and use it in GitHub Desktop.
control french postal code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function validateFrenchPostalCode( | |
input: string, | |
partialControl = false | |
): boolean { | |
// Check length constraints | |
if (input.length > 5 || (!partialControl && input.length !== 5)) { | |
return false; | |
} | |
const finalInput = input.toUpperCase(); | |
// Define valid French department codes | |
const validDepartments = [ | |
...Array.from({ length: 95 }, (_, i) => String(i + 1).padStart(2, '0')), // 01 to 95 | |
'2A', | |
'2B', // Corsica | |
'96', | |
'97', | |
'98', // Overseas territories | |
]; | |
// Validate based on length | |
switch (finalInput.length) { | |
case 1: | |
// First character must be a digit between 0 and 9 | |
return /^[0-9]$/.test(finalInput); | |
case 2: | |
// First two characters must form a valid department code | |
return validDepartments.includes(finalInput); | |
case 3: | |
case 4: | |
case 5: { | |
// First two characters must form a valid department code | |
const departmentCode = finalInput.slice(0, 2); | |
if (!validDepartments.includes(departmentCode)) { | |
return false; | |
} | |
// Remaining characters must be digits | |
const remainingPart = finalInput.slice(2); | |
return /^[0-9]*$/.test(remainingPart); | |
} | |
default: | |
return false; | |
} | |
} | |
console.log(validateFrenchPostalCode('7')); // true | |
console.log(validateFrenchPostalCode('75')); // true | |
console.log(validateFrenchPostalCode('750')); // true | |
console.log(validateFrenchPostalCode('75008')); // true | |
console.log(validateFrenchPostalCode('750089')); // false | |
console.log(validateFrenchPostalCode('2A')); // true | |
console.log(validateFrenchPostalCode('2A1')); // true | |
console.log(validateFrenchPostalCode('2A100')); // true | |
console.log(validateFrenchPostalCode('2A1000')); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment