Created
August 25, 2023 04:55
-
-
Save martinratinaud/9fc0121fb358c24e9cce2db59b6acfe5 to your computer and use it in GitHub Desktop.
Validate SIREN/SIRET with yup
This file contains 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
// Luhn algorithm to validate the SIRET number | |
const luhnCheck = (num?: string) => { | |
if (!num) { | |
return false; | |
} | |
let arr = (num + '') | |
.split('') | |
.reverse() | |
.map((x) => parseInt(x)); | |
let lastDigit = arr.splice(0, 1)[0]; | |
let sum = arr.reduce((acc, val, i) => (i % 2 === 0 ? acc + ((val * 2) % 9) : acc + val), 0); | |
return (sum + lastDigit) % 10 === 0; | |
}; | |
const schema = yup.object({ | |
businessRegistrationId: yup | |
.string() | |
.trim() | |
.matches(/^[0-9]{9}$|^[0-9]{14}$/, 'Le SIRET/SIREN doit faire exactement 9 ou 14 caractères') | |
.test('is-valid-siret', 'SIRET/SIREN invalide', luhnCheck) | |
.required(), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment