Last active
September 19, 2019 18:41
-
-
Save sjsyrek/0ef2c82cbda6981417d38bef7e412715 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
| import Data.Monoid | |
| import Data.Functor | |
| import Control.Applicative | |
| data Validation err a = Failure err | Success a | |
| deriving Show | |
| instance Functor (Validation err) where | |
| fmap f (Success a) = Success (f a) | |
| fmap _ (Failure e) = Failure e | |
| instance Monoid err => Applicative (Validation err) where | |
| pure = Success | |
| Success f <*> Success a = Success (f a) | |
| Success _ <*> Failure e = Failure e | |
| Failure e <*> Success _ = Failure e | |
| Failure e <*> Failure e' = Failure (e <> e') | |
| data Error = | |
| EmptyField | |
| | NotMinLength | |
| deriving Show | |
| data Form = Form { | |
| email :: String | |
| , password :: String | |
| } deriving Show | |
| newtype Email = Email String | |
| newtype Password = Password String | |
| data ValidatedForm = ValidatedForm Email Password | |
| mkForm :: String -> String -> Form | |
| mkForm email password = Form email password | |
| notEmpty :: String -> Validation Error String | |
| notEmpty "" = Failure EmptyField | |
| notEmpty str = Success str | |
| minLength :: String -> Int -> Validation Error String | |
| minLength str n | |
| | length str >= n = Success str | |
| | otherwise = Failure NotMinLength | |
| minPasswordLength :: Int | |
| minPasswordLength = 8 | |
| validateEmail :: String -> Validation Error Email | |
| validateEmail input = | |
| notEmpty input $> | |
| Email input | |
| validatePassword :: String -> Validation Error Password | |
| validatePassword input = | |
| notEmpty input *> | |
| minLength input minPasswordLength *> | |
| Password input | |
| validateForm :: Form -> ValidatedForm | |
| validateForm (Form email password) = | |
| ValidatedForm <$> | |
| validateEmail email <*> | |
| validatePassword password |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment