Last active
March 6, 2019 16:20
-
-
Save adauguet/725b2a429bb5381fbe47ad09656cbbb8 to your computer and use it in GitHub Desktop.
French phone number validation
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 Phone exposing (phoneParser) | |
import Parser exposing ((|.), (|=), Parser, Step(..), andThen, chompWhile, end, getChompedString, loop, oneOf, problem, run, succeed, symbol) | |
-- French phone number validation | |
-- This code makes sure that the phone number has one of the following prefixes: 0033 | +33 | 0. | |
-- This is only used for validation purposes so the prefix is not retained. | |
-- source https://korban.net/posts/elm/2018-09-07-introduction-elm-parser/ | |
whitespace : Parser () | |
whitespace = | |
chompWhile (\c -> c == ' ') | |
countryCode : Parser () | |
countryCode = | |
oneOf | |
[ succeed () | |
|. symbol "+" | |
|. whitespace | |
|. symbol "33" | |
|. whitespace | |
, succeed () | |
|. symbol "00" | |
|. whitespace | |
|. symbol "33" | |
|. whitespace | |
, succeed () | |
|. symbol "0" | |
] | |
localNumber : Parser String | |
localNumber = | |
let | |
checkLength s = | |
if String.length s == 9 then | |
succeed s | |
else | |
problem "A french phone number should have 9 local digits" | |
in | |
localNumberStr | |
|. end | |
|> andThen checkLength | |
localNumberStr : Parser String | |
localNumberStr = | |
loop [] localHelp | |
|> Parser.map String.concat | |
localHelp : List String -> Parser (Step (List String) (List String)) | |
localHelp nums = | |
let | |
checkNum numsSoFar num = | |
if String.length num > 0 then | |
Loop (num :: numsSoFar) | |
else | |
Done (List.reverse numsSoFar) | |
in | |
succeed (checkNum nums) | |
|= (getChompedString <| chompWhile Char.isDigit) | |
|. whitespace | |
phoneParser : Parser String | |
phoneParser = | |
succeed identity | |
|. countryCode | |
|= localNumber |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment