Last active
December 17, 2023 12:04
-
-
Save pre63/fd2ae5a305c9d260a8a0a5403a14b21f to your computer and use it in GitHub Desktop.
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
| module Parsers.Phone exposing (format, isValid) | |
| import PhoneNumber | |
| import PhoneNumber.Countries exposing (all, countryUS) | |
| import String exposing (dropLeft, left, replace, startsWith) | |
| parse : String -> Bool | |
| parse number = | |
| PhoneNumber.valid | |
| { defaultCountry = countryUS | |
| , otherCountries = all | |
| , types = PhoneNumber.anyType | |
| } | |
| number | |
| sanitize : String -> String | |
| sanitize = | |
| replace "+" "" >> replace "(" "" >> replace ")" "" >> replace "-" "" >> replace " " "" | |
| isValid : String -> Bool | |
| isValid = | |
| sanitize >> validate | |
| validate : String -> Bool | |
| validate number = | |
| if startsWith "555" number then | |
| -- 555 numbers are reserved for fictional use. | |
| False | |
| else if (startsWith "555" << dropLeft 3) number then | |
| -- 555 numbers are reserved for fictional use. | |
| False | |
| else if parse number then | |
| True | |
| else | |
| parse ("+" ++ number) | |
| tryGetNumberInfo : String -> Maybe ( PhoneNumber.Country, List PhoneNumber.NumberType ) | |
| tryGetNumberInfo = | |
| List.head | |
| << PhoneNumber.matches | |
| { defaultCountry = countryUS | |
| , otherCountries = all | |
| , types = PhoneNumber.anyType | |
| } | |
| tryGetCountryCode : String -> Maybe String | |
| tryGetCountryCode number = | |
| Maybe.map (.countryCode << Tuple.first) <| | |
| List.head <| | |
| List.filterMap identity <| | |
| List.map tryGetNumberInfo [ "+" ++ number, "+1" ++ number ] | |
| dropCountryCode : String -> String -> String | |
| dropCountryCode cc number = | |
| if startsWith cc number then | |
| dropLeft (String.length cc) number | |
| else | |
| number | |
| usFormat : String -> String | |
| usFormat n = | |
| -- U.S. format without the country code | |
| "(" ++ left 3 n ++ ") " ++ left 3 (dropLeft 3 n) ++ "-" ++ left 4 (dropLeft 6 n) | |
| format : String -> String | |
| format number = | |
| -- this prser formatter will take in any number, | |
| -- satize it and then format it to the international format | |
| let | |
| new = | |
| sanitize number | |
| in | |
| case tryGetCountryCode new of | |
| Just "1" -> | |
| usFormat <| dropCountryCode "1" new | |
| Just cc -> | |
| "+" ++ cc ++ " " ++ dropCountryCode cc new | |
| Nothing -> | |
| number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment