Skip to content

Commit

Permalink
refactor(validations): Use functor pattern to clean the validations
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin COMBRIAT committed Jan 15, 2021
1 parent 2090453 commit d309352
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 25 deletions.
4 changes: 4 additions & 0 deletions example/App.res
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ module MakeForm = Formidable.Make(Validations.Label, I18n.Error)
// all the validations and input components will just work, and the creation of a new form is trivial
module Form = MakeForm(Values)

module Validations = Validations.Make(Values)

open Formidable.Validations

open Validations

// Validations can be defined in an other module, and re-used easily
Expand Down
56 changes: 31 additions & 25 deletions example/Validations.res
Original file line number Diff line number Diff line change
@@ -1,36 +1,42 @@
include Formidable.Validations
open Formidable.Validations

module Label = {
type t = [#required | #email | #equals]
}

let required = (
#name(#required),
({Validator.Args.label: label, value}) =>
module Make = (
Values: {
type t
},
) => {
module Description = Description.Make(Values, Label)

let required = Description.make(~name=#required, ({label, value}) =>
switch value {
| "" => #error(#error(("required", label)))
| _ => #ok(value)
},
)
}
)

let emailRegEx = %re("/.+@.+/")
let emailRegEx = %re("/.+@.+/")

let email = (
#name(#email),
({Validator.Args.label: label, value}) =>
if emailRegEx->Js.Re.test_(value) {
#ok(value)
} else {
#error(#error(("email", label)))
},
)
let email = (
#name(#email),
({Validator.Args.label: label, value}) =>
if emailRegEx->Js.Re.test_(value) {
#ok(value)
} else {
#error(#error(("email", label)))
},
)

let equals = lens => (
#name(#equals),
({Validator.Args.label: label, value, values}) =>
if lens.Optic.Lens.get(values) == value {
#ok(value)
} else {
#error(#error(("equals", label)))
},
)
let equals = lens => (
#name(#equals),
({Validator.Args.label: label, value, values}) =>
if lens.Optic.Lens.get(values) == value {
#ok(value)
} else {
#error(#error(("equals", label)))
},
)
}
11 changes: 11 additions & 0 deletions src/FormidableValidations.res
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ The second one is used only internally when composing validations`)
}

type t<'values, 'value, 'error, 'label> = (kind<'label>, Validator.t<'values, 'value, 'error>)

module Make = (
Values: {
type t
},
Label: {
type t
},
) => {
let make = (~name, validator): t<Values.t, _, _, Label.t> => (#name(name), validator)
}
}

type t<'values, 'value, 'error, 'label> = (
Expand Down

0 comments on commit d309352

Please sign in to comment.