Skip to content

Commit

Permalink
feat: add phone type
Browse files Browse the repository at this point in the history
  • Loading branch information
treboryx committed Apr 6, 2023
1 parent 219a87e commit 3a1db3e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
18 changes: 18 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,21 @@ export const luhnChecksumValidate = (

return sum % digits.length === 0;
};

export const addPrefixForMobile = (number: string): string => {
const pregix = "+30";
const cleanedNumber = number.replace(/[\s\-()\.]/g, "");

// Check if the phone number starts with the Greek international prefix or '0030'
if (cleanedNumber.startsWith(pregix) || cleanedNumber.startsWith("0030")) {
return cleanedNumber;
}

// If the phone number starts with '69' (mobile), add the international prefix
if (cleanedNumber.startsWith("69")) {
return pregix + cleanedNumber;
}

// If the phone number doesn't match the expected formats, return the original phone number
return number;
};
17 changes: 12 additions & 5 deletions src/validators/phone.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
type PhoneNumberType = "mobile" | "landline" | "";

/**
* Validates Greek mobile and landline phone numbers.
*
* @param {string} value - The phone number to validate.
* @param {PhoneNumberType} [type] - Optional. The type of phone number to validate ('mobile', 'landline', or ''). Defaults to '' (both).
* @returns {boolean} - Returns true if the phone number is valid, otherwise false.
*/
export default (value: string): boolean => {
export default (value: string, type: PhoneNumberType = ""): boolean => {
const cleanedValue = value.replace(/[\s\-()\.]/g, "");

// Validate mobile numbers
const mobileRegex = /^(\+30|0030)?69\d{8}$/;
if (mobileRegex.test(cleanedValue)) {
return true;
if (type === "mobile" || type === "") {
if (mobileRegex.test(cleanedValue)) {
return true;
}
}

// Validate landline numbers with area codes
const landlineRegex = /^(\+30|0030)?(2\d{9}|801\d{7})$/;
if (landlineRegex.test(cleanedValue)) {
return true;
if (type === "landline" || type === "") {
if (landlineRegex.test(cleanedValue)) {
return true;
}
}

return false;
Expand Down
4 changes: 4 additions & 0 deletions test/isPhone.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,8 @@ describe.concurrent("isPhone", () => {
it("00302101234567", () => {
expect(isPhone("00302101234567")).toBe(true);
});

it("00302101234567", () => {
expect(isPhone("00302101234567", "mobile")).toBe(false);
});
});

0 comments on commit 3a1db3e

Please sign in to comment.