@@ -2,7 +2,7 @@ module Lumi.Components.Form.Validation
2
2
( Validator
3
3
, nonEmpty , nonEmptyArray , nonNull
4
4
, mustEqual , mustBe
5
- , validNumber , validInt
5
+ , validNumber , validInt , validDate
6
6
, optional
7
7
, Validated (..)
8
8
, _Validated , _Fresh , _Modified
@@ -18,7 +18,9 @@ import Prelude
18
18
import Data.Array as Array
19
19
import Data.Array.NonEmpty (NonEmptyArray )
20
20
import Data.Array.NonEmpty (fromArray ) as NEA
21
+ import Data.Date as Date
21
22
import Data.Either (Either (..), either , hush , note )
23
+ import Data.Enum (toEnum )
22
24
import Data.Eq (class Eq1 )
23
25
import Data.Foldable (foldMap )
24
26
import Data.Int as Int
@@ -29,8 +31,11 @@ import Data.Newtype (un)
29
31
import Data.Nullable (notNull )
30
32
import Data.Number as Number
31
33
import Data.Ord (class Ord1 )
34
+ import Data.String.Common (split )
32
35
import Data.String.NonEmpty (NonEmptyString )
33
36
import Data.String.NonEmpty (fromString ) as NES
37
+ import Data.String.Pattern (Pattern (..))
38
+ import Data.Traversable (traverse )
34
39
import Heterogeneous.Mapping (class HMap , class MapRecordWithIndex , class Mapping , ConstMapping , hmap , mapping )
35
40
import Lumi.Components.Column (column_ )
36
41
import Lumi.Components.Form.Internal (Forest , FormBuilder (..), Tree (..))
@@ -81,6 +86,16 @@ validNumber name = note (name <> " must be a number.") <<< Number.fromString
81
86
validInt :: String -> Validator String Int
82
87
validInt name = note (name <> " must be a whole number." ) <<< Int .fromString
83
88
89
+ -- | A `Validator` which verifies that its input can be parsed as a date.
90
+ -- | Dates are of the format "YYYY-MM-DD".
91
+ validDate :: String -> Validator String Date.Date
92
+ validDate name input =
93
+ note (name <> " must be a date." ) result
94
+ where
95
+ result = case traverse Int .fromString $ split (Pattern " -" ) input of
96
+ Just [y, m, d] -> join $ Date .exactDate <$> toEnum y <*> toEnum m <*> toEnum d
97
+ _ -> Nothing
98
+
84
99
-- | Modify a `Validator` to accept empty strings in addition to anything it
85
100
-- | already accepts. The empty string is mapped to `Nothing`, and any other
86
101
-- | valid input is mapped to `Just` the result of the original validator.
0 commit comments