From a4e404c77637c3b7e13a702186f21d68c6b1419f Mon Sep 17 00:00:00 2001 From: "Gabriel R. Abreu" Date: Wed, 29 Jul 2020 18:29:32 -0300 Subject: [PATCH] feat(reschema): validator helpers --- packages/demo/src/modules/PostAddNext.re | 35 ++++++++++++--------- packages/reschema/src/ReSchema.re | 40 ++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 15 deletions(-) diff --git a/packages/demo/src/modules/PostAddNext.re b/packages/demo/src/modules/PostAddNext.re index 4072cb10..5ecccb06 100644 --- a/packages/demo/src/modules/PostAddNext.re +++ b/packages/demo/src/modules/PostAddNext.re @@ -41,21 +41,26 @@ let make = () => { PostAddForm.use( ~validationStrategy=OnDemand, ~schema={ - PostAddForm.Validation.Schema([| - Custom( - Title, - values => - Js.String.length(values.title) > 20 - ? Error("Keep it short!") : Valid, - ), - StringNonEmpty(Description), - Custom( - AcceptTerms, - values => - values.acceptTerms == false - ? Error("You must accept all the terms") : Valid, - ), - |]); + PostAddForm.Validation.( + Schema( + string(~min=12, Title) + @ custom( + ~predicate= + values => + Js.String.length(values.title) > 20 + ? Error("Keep it short!") : Valid, + Title, + ) + @ nonEmpty(Description) + @ custom( + ~predicate= + values => + values.acceptTerms == false + ? Error("You must accept all the terms") : Valid, + AcceptTerms, + ), + ) + ); }, ~onSubmit= ({state}) => { diff --git a/packages/reschema/src/ReSchema.re b/packages/reschema/src/ReSchema.re index f5c9f894..1a05a745 100644 --- a/packages/reschema/src/ReSchema.re +++ b/packages/reschema/src/ReSchema.re @@ -32,6 +32,46 @@ module Make = (Lenses: Lenses) => { | Custom(Lenses.field('a), Lenses.state => fieldState): t; type schema = | Schema(array(t)): schema; + + let (@) = (a, b) => a->Belt.Array.concat(b); + let ( { + switch (maybeArr) { + | Some(someArr) => arr @ [|someArr|] + | None => arr + }; + }; + + let custom = (~predicate, field) => { + [|Custom(field, predicate)|]; + }; + + let email = field => [|Email(field)|]; + + let nonEmpty = field => [|StringNonEmpty(field)|]; + + let string = (~min=?, ~max=?, field) => { + Belt.Option.( + [||] + map(min => StringMin(field, min)) + map(max => StringMax(field, max)) + ); + }; + + let float = (~min=?, ~max=?, field) => { + Belt.Option.( + [||] + map(min => FloatMin(field, min)) + map(max => FloatMax(field, max)) + ); + }; + + let int = (~min=?, ~max=?, field) => { + Belt.Option.( + [||] + map(min => IntMin(field, min)) + map(max => IntMax(field, max)) + ); + }; }; module RegExps = {