Skip to content

Commit

Permalink
feat(reschema): validator helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
fakenickels committed Jul 29, 2020
1 parent c4dd831 commit a4e404c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 15 deletions.
35 changes: 20 additions & 15 deletions packages/demo/src/modules/PostAddNext.re
Original file line number Diff line number Diff line change
Expand Up @@ -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}) => {
Expand Down
40 changes: 40 additions & 0 deletions packages/reschema/src/ReSchema.re
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<?) = (arr, maybeArr) => {
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.(
[||]
<? min->map(min => StringMin(field, min))
<? max->map(max => StringMax(field, max))
);
};

let float = (~min=?, ~max=?, field) => {
Belt.Option.(
[||]
<? min->map(min => FloatMin(field, min))
<? max->map(max => FloatMax(field, max))
);
};

let int = (~min=?, ~max=?, field) => {
Belt.Option.(
[||]
<? min->map(min => IntMin(field, min))
<? max->map(max => IntMax(field, max))
);
};
};

module RegExps = {
Expand Down

0 comments on commit a4e404c

Please # to comment.