Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return an union type in Validation functions #19

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions example/Example.res
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module Form = {
"lastName": "",
"acceptTerms": false,
"hobbies": [{"name": ""}],
"location": "",
}),
(),
),
Expand Down Expand Up @@ -52,13 +53,17 @@ module Form = {
(
"validEmail",
Validation.sync(value =>
value->ReCode.Decode.string->Belt.Result.getWithDefault("")->String.contains('@')
ValidationResult.boolResult(
value->ReCode.Decode.string->Belt.Result.getWithDefault("")->String.contains('@'),
)
),
),
(
"validLength",
Validation.sync(value =>
value->ReCode.Decode.string->Belt.Result.getWithDefault("")->String.length >= 8
ValidationResult.boolResult(
value->ReCode.Decode.string->Belt.Result.getWithDefault("")->String.length >= 8,
)
),
),
]),
Expand Down Expand Up @@ -139,6 +144,30 @@ module Form = {
<ErrorMessage errors name message={"Required"->React.string} />
</div>}
/>
<Controller
name=Values.location
control
rules={Rules.make(
~required=true,
~validate=Js.Dict.fromArray([
("minThreeChars", Validations.minThreeChars),
("maxTenChars", Validations.maxTenChars),
]),
(),
)}
render={({field: {name, onBlur, onChange, ref, value}}) =>
<div>
<label> {name->React.string} </label>
<input
name
onBlur={_event => onBlur()}
onChange={event => onChange(Controller.OnChangeArg.event(event))}
ref
value={value->ReCode.Decode.string->Belt.Result.getWithDefault("")}
/>
<ErrorMessage errors name message={"Required"->React.string} />
</div>}
/>
<Controller
name=Values.acceptTerms
control
Expand Down
23 changes: 23 additions & 0 deletions example/Validations.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@ocaml.doc(
"Custom validator fuction to check that the input has at least three characters. Will return a boolean."
)
let minThreeCharsValue = value => {
let decodedValue = value->Js.Json.decodeString->Belt.Option.getWithDefault("")

ValidationResult.boolResult(decodedValue->Js.String2.length >= 3)
}

let minThreeChars = Validation.sync(minThreeCharsValue)

@ocaml.doc(
"Custom validator fuction to check that the input has at most ten characters. Will throw a custom error otherwise."
)
let maxTenCharsValue = value => {
let decodedValue = value->Js.Json.decodeString->Belt.Option.getWithDefault("")

decodedValue->Js.String2.length > 10
? ValidationResult.stringResult("There are over ten characters in this input.")
: ValidationResult.boolResult(true)
}

let maxTenChars = Validation.syncWithCustomError(maxTenCharsValue)
7 changes: 6 additions & 1 deletion example/Values.res
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,24 @@ type t = {
email: string,
firstName: string,
lastName: string,
location: string,
acceptTerms: bool,
hobbies: array<Hobby.t>,
}

let email = "email"
let firstName = "firstName"
let lastName = "lastName"
let location = "location"
let acceptTerms = "acceptTerms"
let hobbies = "hobbies"
let hobby = index => `${hobbies}.${index->Belt.Int.toString}.${Hobby.name}`

let make = (email, firstName, lastName, acceptTerms, hobbies) => {
let make = (email, firstName, lastName, acceptTerms, hobbies, location) => {
email: email,
firstName: firstName,
lastName: lastName,
location: location,
acceptTerms: acceptTerms,
hobbies: hobbies,
}
Expand All @@ -52,6 +55,7 @@ let decoder = {
->Object.required(lastName, string)
->Object.required(acceptTerms, bool)
->Object.required(hobbies, array(Hobby.decoder))
->Object.required(location, string)
}

let encoder = values => {
Expand All @@ -61,6 +65,7 @@ let encoder = values => {
(email, string(values["email"])),
(firstName, string(values["firstName"])),
(lastName, string(values["lastName"])),
(location, string(values["location"])),
(acceptTerms, bool(values["acceptTerms"])),
(hobbies, array(Hobby.encoder, values["hobbies"])),
])
Expand Down
4 changes: 4 additions & 0 deletions src/Validation.res
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ type rec t = Any('a): t

let sync = syncHandler => Any(syncHandler)

let syncWithCustomError = syncHandler => Any(syncHandler)

let async = asyncHandler => Any(asyncHandler)

let asyncWithCustomError = asyncHandler => Any(asyncHandler)
8 changes: 6 additions & 2 deletions src/Validation.resi
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
type rec t

@ocaml.doc("Synchronous validation")
let sync: (Js.Json.t => bool) => t
let sync: (Js.Json.t => ValidationResult.t) => t

let syncWithCustomError: (Js.Json.t => ValidationResult.t) => t

@ocaml.doc("Asynchronous validation")
let async: (Js.Json.t => Js.Promise.t<bool>) => t
let async: (Js.Json.t => Js.Promise.t<ValidationResult.t>) => t

let asyncWithCustomError: (Js.Json.t => Js.Promise.t<ValidationResult.t>) => t
5 changes: 5 additions & 0 deletions src/ValidationResult.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@unboxed type rec t = Any('value): t

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't seem to understand this line. Can you explain it in more details? And why should we wrap the handler with Any?


let boolResult = validationResult => Any(validationResult)

let stringResult = validationResult => Any(validationResult)
8 changes: 8 additions & 0 deletions src/ValidationResult.resi
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@ocaml.doc(
"The union type for the result of a validator function; allows validation functions to return either boolean or a string"
)
type rec t

let boolResult: bool => t

let stringResult: string => t