Skip to content

Instantly share code, notes, and snippets.

@martinratinaud
Created August 25, 2023 04:55
Show Gist options
  • Save martinratinaud/9fc0121fb358c24e9cce2db59b6acfe5 to your computer and use it in GitHub Desktop.
Save martinratinaud/9fc0121fb358c24e9cce2db59b6acfe5 to your computer and use it in GitHub Desktop.
Validate SIREN/SIRET with yup
// 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