aboutsummaryrefslogtreecommitdiff
path: root/common/src/Common/Validation/Atomic.hs
blob: 351666810e94ee35b24d516fd784cf89a42c5eeb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module Common.Validation.Atomic
  ( nonEmpty
  , minLength
  , number
  , nonNullNumber
  , day
  ) where

import           Data.Text          (Text)
import qualified Data.Text          as T
import           Data.Time.Calendar (Day)
import           Data.Validation    (Validation)
import qualified Data.Validation    as V
import qualified Text.Read          as T

import qualified Common.Msg         as Msg
import qualified Common.Util.Time   as Time

minLength :: Int -> Text -> Validation Text Text
minLength l =
  V.validate
    (Msg.get (Msg.Form_MinChars l))
    (\t -> if T.length t >= l then Just t else Nothing)

nonEmpty :: Text -> Validation Text Text
nonEmpty =
  V.validate
    (Msg.get Msg.Form_NonEmpty)
    (\t -> if (not . T.null $ t) then Just t else Nothing)

number :: Text -> Validation Text Int
number input =
  case (T.readMaybe . T.unpack $ input) of
    Just n -> V.Success n
    _      -> V.Failure (Msg.get Msg.Form_InvalidInt)

nonNullNumber :: Int -> Validation Text Int
nonNullNumber =
  V.validate
    (Msg.get Msg.Form_NonNullNumber)
    (\n -> if n /= 0 then Just n else Nothing)

day :: Text ->  Validation Text Day
day str =
  case Time.parseDay str of
    Just d  -> V.Success d
    Nothing -> V.Failure $ Msg.get Msg.Form_InvalidDate