/**
* Calcule l'age d'un utilisateur a partir de sa date de naissance.
* @param {{ birth: Date }} p Objet contenant la date de naissance.
* @returns {number} Age calcule ou `NaN` si la date est invalide.
* @throws {Error} Si le parametre est absent ou invalide.
*/
export function calculateAge(p) {
if (!p) {
throw new Error("missing param p");
}
if (typeof p !== "object" || !(p.birth instanceof Date)) {
throw new Error("invalid param p");
}
const birthTime = p.birth.getTime();
if (Number.isNaN(birthTime)) {
return NaN;
}
const today = new Date();
let age = today.getFullYear() - p.birth.getFullYear();
const monthDiff = today.getMonth() - p.birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < p.birth.getDate())) {
age -= 1;
}
return age;
}
/**
* Verifie si un code postal respecte le format francais.
* @param {string|number} cp Code postal a verifier.
* @returns {boolean} `true` si le code postal contient exactement 5 chiffres.
* @throws {Error} Si le parametre est absent.
*/
export function isCPValid(cp) {
if (!cp) {
throw new Error("missing param cp");
}
const cpRegex = /^\d{5}$/;
return cpRegex.test(String(cp).trim());
}
/**
* Verifie si un utilisateur est majeur.
* @param {{ birth: Date }} p Objet contenant la date de naissance.
* @returns {boolean} `true` si l'utilisateur a au moins 18 ans.
* @throws {Error} Si le parametre est absent.
*/
export function isUserMajeur(p) {
if (!p) {
throw new Error("missing param p");
}
const age = calculateAge(p);
return age >= 18;
}
/**
* Verifie le format d'une adresse email.
* @param {string} email Adresse email a verifier.
* @returns {boolean} `true` si le format est valide.
* @throws {Error} Si le parametre est absent.
*/
export function isEmailValid(email) {
if (!email) {
throw new Error("missing param email");
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(String(email).trim());
}
/**
* Verifie un champ texte de type nom, prenom ou ville.
* @param {string} str Valeur a verifier.
* @returns {boolean} `true` si la chaine respecte le format attendu.
* @throws {Error} Si le parametre est absent.
*/
export function isStringValide(str) {
if (!str) {
throw new Error("missing param str");
}
if (typeof str !== "string") {
return false;
}
const normalizedValue = str.trim();
const validStringRegex = /^[A-Za-zÀ-ÖØ-öø-ÿ]+(?:[ '-][A-Za-zÀ-ÖØ-öø-ÿ]+)*$/u;
return validStringRegex.test(normalizedValue);
}