-
-
Notifications
You must be signed in to change notification settings - Fork 16
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
Introduce Oxpecker.ModelValidation #33
Merged
Merged
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
70a89aa
Introduce Oxpecker.ModelValidation
Lanayx 7660140
Fantomas formatting
Lanayx 609a422
Fixed NRT warnings
Lanayx a6d9b3f
Updated validation doc
Lanayx a5f0a77
Updated validation doc
Lanayx 61fef4c
Removed redundant section
Lanayx 2e4f0a4
Added several documentation comments
Lanayx 177ada7
Release notes updated
Lanayx b05c084
Changed Seq.empty to Array.empty to avoid serialization issue
Lanayx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,38 @@ | ||
namespace ContactApp.templates.shared | ||
|
||
open ContactApp.templates.shared.errors | ||
open Oxpecker.Htmx | ||
open Oxpecker.ModelValidation | ||
|
||
module contactFields = | ||
|
||
open ContactApp.Models | ||
open Oxpecker.ViewEngine | ||
|
||
let html (contact: ContactDTO) = | ||
let html (contact: ModelState<ContactDTO>) = | ||
let x = Unchecked.defaultof<ContactDTO> | ||
let showErrors = showErrors contact | ||
div() { | ||
p() { | ||
label(for'="email") { "Email" } | ||
input(name="email", id="email", type'="email", placeholder="Email", value=contact.email, | ||
input(name=nameof x.email, id="email", type'="email", placeholder="Email", value=contact.Value(_.email), | ||
hxTrigger="change, keyup delay:200ms changed", | ||
hxGet= $"/contacts/{contact.id}/email", hxTarget="next .error") | ||
span(class'="error") { contact.GetError("email") } | ||
hxGet= $"/contacts/{contact.Value(_.id >> string)}/email", hxTarget="next .error") | ||
showErrors <| nameof x.email | ||
} | ||
p() { | ||
label(for'="first") { "First Name" } | ||
input(name="first", id="firs", type'="text", placeholder="First Name", value=contact.first) | ||
span(class'="error") { contact.GetError("first") } | ||
input(name=nameof x.first, id="first", type'="text", placeholder="First Name", value=contact.Value(_.first)) | ||
showErrors <| nameof x.first | ||
} | ||
p() { | ||
label(for'="last") { "Last Name" } | ||
input(name="last", id="last", type'="text", placeholder="Last Name", value=contact.last) | ||
span(class'="error") { contact.GetError("last") } | ||
input(name=nameof x.last, id="last", type'="text", placeholder="Last Name", value=contact.Value(_.last)) | ||
showErrors <| nameof x.last | ||
} | ||
p() { | ||
label(for'="phone") { "Phone" } | ||
input(name="phone", id="phone", type'="text", placeholder="Phone", value=contact.phone) | ||
span(class'="error") { contact.GetError("phone") } | ||
input(name=nameof x.phone, id="phone", type'="text", placeholder="Phone", value=contact.Value(_.phone)) | ||
showErrors <| nameof x.phone | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
module ContactApp.templates.shared.errors | ||
|
||
open Oxpecker.ViewEngine | ||
open Oxpecker.ModelValidation | ||
|
||
let showErrors (modelState: ModelState<_>) (fieldName: string) = | ||
match modelState with | ||
| ModelState.Invalid (_, modelErrors) -> | ||
span(class'="error"){ | ||
modelErrors.ErrorMessagesFor(fieldName) |> String.concat ", " | ||
} :> HtmlElement | ||
| _ -> | ||
Fragment() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
namespace Oxpecker | ||
|
||
[<AutoOpen>] | ||
module ModelValidation = | ||
|
||
open System.Collections.Generic | ||
open System.ComponentModel.DataAnnotations | ||
open System.Runtime.CompilerServices | ||
open Microsoft.AspNetCore.Http | ||
|
||
type ValidationErrors (errors: ResizeArray<ValidationResult>) = | ||
let errorDict = lazy ( | ||
let dict = Dictionary<string,ResizeArray<string>>() | ||
for error in errors do | ||
for memberName in error.MemberNames do | ||
match dict.TryGetValue(memberName) with | ||
| true, value -> | ||
value.Add(error.ErrorMessage) | ||
| false, _ -> | ||
let arrayList = ResizeArray(1) | ||
arrayList.Add(error.ErrorMessage) | ||
dict[memberName] <- arrayList | ||
dict | ||
) | ||
member this.All: ValidationResult seq = errors | ||
member this.ErrorMessagesFor(name): string seq = | ||
match errorDict.Value.TryGetValue(name) with | ||
| true, value -> value | ||
| false, _ -> Seq.empty | ||
|
||
type InvalidModel<'T> = 'T * ValidationErrors | ||
|
||
[<RequireQualifiedAccess>] | ||
type ModelState<'T> = | ||
| Empty | ||
| Valid of 'T | ||
| Invalid of InvalidModel<'T> | ||
member this.Value(f: 'T -> string|null) = | ||
match this with | ||
| Empty -> null | ||
| Valid model -> f model |> string | ||
| Invalid (model, _) -> f model |> string | ||
member this.BoolValue(f: 'T -> bool) = | ||
match this with | ||
| Empty -> false | ||
| Valid model -> f model | ||
| Invalid (model, _) -> f model | ||
|
||
[<RequireQualifiedAccess>] | ||
type ValidationResult<'T> = | ||
| Valid of 'T | ||
| Invalid of InvalidModel<'T> | ||
|
||
let validateModel (model: 'T) = | ||
let validationResults = ResizeArray() | ||
match Validator.TryValidateObject(model, ValidationContext(model), validationResults, true) with | ||
| true -> ValidationResult.Valid model | ||
| false -> ValidationResult.Invalid (model, ValidationErrors(validationResults)) | ||
|
||
type HttpContextExtensions = | ||
|
||
/// <summary> | ||
/// Uses the <see cref="Serializers.IJsonSerializer"/> to deserialize the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously into an object of type 'T and then validate it. | ||
/// </summary> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>Returns a <see cref="System.Threading.Tasks.Task{T}"/></returns> | ||
[<Extension>] | ||
static member BindAndValidateJson<'T>(ctx: HttpContext) = | ||
task { | ||
let! result = ctx.BindJson<'T>() | ||
return validateModel result | ||
} | ||
|
||
/// <summary> | ||
/// Parses all input elements from an HTML form into an object of type 'T and then validates it. | ||
/// </summary> | ||
/// <param name="ctx">The current http context object.</param> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>Returns a <see cref="System.Threading.Tasks.Task{T}"/></returns> | ||
[<Extension>] | ||
static member BindAndValidateForm<'T>(ctx: HttpContext) = | ||
task { | ||
let! result = ctx.BindForm<'T>() | ||
return validateModel result | ||
} | ||
|
||
/// <summary> | ||
/// Parses all parameters of a request's query string into an object of type 'T and then validates it. | ||
/// </summary> | ||
/// <param name="ctx">The current http context object.</param> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>Returns an instance of type 'T</returns> | ||
[<Extension>] | ||
static member BindAndValidateQuery<'T>(ctx: HttpContext) = | ||
let result = ctx.BindQuery<'T>() | ||
validateModel result | ||
|
||
[<AutoOpen>] | ||
module RequestHandlers = | ||
/// <summary> | ||
/// Parses a JSON payload into an instance of type 'T and validates it. | ||
/// </summary> | ||
/// <param name="f">A function which accepts an object of type ValidationResult<'T> and returns a <see cref="EndpointHandler"/> function.</param> | ||
/// <param name="ctx">HttpContext</param> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>An Oxpecker <see cref="EndpointHandler"/> function which can be composed into a bigger web application.</returns> | ||
let bindAndValidateJson<'T> (f: ValidationResult<'T> -> EndpointHandler) : EndpointHandler = | ||
fun (ctx: HttpContext) -> | ||
task { | ||
let! model = ctx.BindJson<'T>() | ||
return! f (validateModel model) ctx | ||
} | ||
|
||
/// <summary> | ||
/// Parses a HTTP form payload into an instance of type 'T and validates it. | ||
/// </summary> | ||
/// <param name="f">A function which accepts an object of type 'T and returns a <see cref="EndpointHandler"/> function.</param> | ||
/// <param name="ctx">HttpContext</param> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>An Oxpecker <see cref="EndpointHandler"/> function which can be composed into a bigger web application.</returns> | ||
let bindAndValidateForm<'T> (f: ValidationResult<'T> -> EndpointHandler) : EndpointHandler = | ||
fun (ctx: HttpContext) -> | ||
task { | ||
let! model = ctx.BindForm<'T>() | ||
return! f (validateModel model) ctx | ||
} | ||
|
||
/// <summary> | ||
/// Parses a HTTP query string into an instance of type 'T and validates it. | ||
/// </summary> | ||
/// <param name="f">A function which accepts an object of type 'T and returns a <see cref="EndpointHandler"/> function.</param> | ||
/// <param name="ctx">HttpContext</param> | ||
/// <typeparam name="'T"></typeparam> | ||
/// <returns>An Oxpecker <see cref="EndpointHandler"/> function which can be composed into a bigger web application.</returns> | ||
let bindAndValidateQuery<'T> (f: ValidationResult<'T> -> EndpointHandler) : EndpointHandler = | ||
fun (ctx: HttpContext) -> | ||
let model = ctx.BindQuery<'T>() | ||
f (validateModel model) ctx |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would this be better/more idiomatic as an
Option<string>
? Curious why the nullability here. I don't write F# in my day job, so I might be missing some nuance.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, the nuance is that it should be mostly used to set
value
attribute of the input and that has typestring | null
for performance and DX reasons. So I tried to match types here to avoid unnecessary conversions.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh that makes a lot of sense! Thanks for the explanation