From a7b46128f9201f85fe9d6913c67d5774b79b8b27 Mon Sep 17 00:00:00 2001 From: DamianEdwards Date: Wed, 7 Jul 2021 13:14:07 -0700 Subject: [PATCH] Initial commit --- .gitattributes | 63 +++ .gitignore | 363 ++++++++++++++++++ MinimalValidation.sln | 46 +++ README.md | 99 +++++ samples/Samples.Console/Program.cs | 30 ++ .../Samples.Console/Samples.Console.csproj | 12 + samples/Samples.Web/Program.cs | 38 ++ .../Properties/launchSettings.json | 28 ++ samples/Samples.Web/Samples.Web.csproj | 12 + .../Samples.Web/appsettings.Development.json | 9 + samples/Samples.Web/appsettings.json | 10 + src/MinimalValidation/MinimalValidation.cs | 145 +++++++ .../MinimalValidation.csproj | 24 ++ 13 files changed, 879 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 MinimalValidation.sln create mode 100644 README.md create mode 100644 samples/Samples.Console/Program.cs create mode 100644 samples/Samples.Console/Samples.Console.csproj create mode 100644 samples/Samples.Web/Program.cs create mode 100644 samples/Samples.Web/Properties/launchSettings.json create mode 100644 samples/Samples.Web/Samples.Web.csproj create mode 100644 samples/Samples.Web/appsettings.Development.json create mode 100644 samples/Samples.Web/appsettings.json create mode 100644 src/MinimalValidation/MinimalValidation.cs create mode 100644 src/MinimalValidation/MinimalValidation.csproj diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/MinimalValidation.sln b/MinimalValidation.sln new file mode 100644 index 0000000..51fb54e --- /dev/null +++ b/MinimalValidation.sln @@ -0,0 +1,46 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30114.105 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{751FE268-A797-46FE-AEE0-BD35D91BE850}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MinimalValidation", "src\MinimalValidation\MinimalValidation.csproj", "{60C03B53-10AC-4D37-BA95-7EEFE2FC61FC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{BF473532-A97B-4CEE-9673-9D4B57D8C1C4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Samples.Console", "samples\Samples.Console\Samples.Console.csproj", "{75062336-DE25-4EBF-9EC5-0465D37D4623}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Samples.Web", "samples\Samples.Web\Samples.Web.csproj", "{DBDC0E13-44E1-42E8-8751-FF5D3313D538}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {60C03B53-10AC-4D37-BA95-7EEFE2FC61FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {60C03B53-10AC-4D37-BA95-7EEFE2FC61FC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {60C03B53-10AC-4D37-BA95-7EEFE2FC61FC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60C03B53-10AC-4D37-BA95-7EEFE2FC61FC}.Release|Any CPU.Build.0 = Release|Any CPU + {75062336-DE25-4EBF-9EC5-0465D37D4623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {75062336-DE25-4EBF-9EC5-0465D37D4623}.Debug|Any CPU.Build.0 = Debug|Any CPU + {75062336-DE25-4EBF-9EC5-0465D37D4623}.Release|Any CPU.ActiveCfg = Release|Any CPU + {75062336-DE25-4EBF-9EC5-0465D37D4623}.Release|Any CPU.Build.0 = Release|Any CPU + {DBDC0E13-44E1-42E8-8751-FF5D3313D538}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DBDC0E13-44E1-42E8-8751-FF5D3313D538}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DBDC0E13-44E1-42E8-8751-FF5D3313D538}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DBDC0E13-44E1-42E8-8751-FF5D3313D538}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {60C03B53-10AC-4D37-BA95-7EEFE2FC61FC} = {751FE268-A797-46FE-AEE0-BD35D91BE850} + {75062336-DE25-4EBF-9EC5-0465D37D4623} = {BF473532-A97B-4CEE-9673-9D4B57D8C1C4} + {DBDC0E13-44E1-42E8-8751-FF5D3313D538} = {BF473532-A97B-4CEE-9673-9D4B57D8C1C4} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {23EC839A-3D4A-43DC-A6B4-A641D51BF0A6} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md new file mode 100644 index 0000000..65582df --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# Minimal Validation +A minimal validation library built atop the existing features in .NET's `System.ComponentModel.DataAnnotations` namespace. Adds support for single-line validation calls and recursion with cycle detection. + +Supports .NET Standard 2.0 compliant runtimes. + +## Installation +The library will soon be available on NuGet, just hold tight! Until then you can copy [the code](src/MinimalValidation/MinimalValidation.cs) directly from this repo. + +## Example usage + +### Console app +```csharp +using System; +using System.ComponentModel.DataAnnotations; + +var title = args.Length > 0 ? args[0] : ""; +var widget = new Widget { Name = title }; + +if (!MinimalValidation.TryValidate(widget, out var errors)) +{ + Console.WriteLine($"{nameof(Widget)} has errors!"); + foreach (var entry in errors) + { + Console.WriteLine($" {entry.Key}:"); + foreach (var error in entry.Value) + { + Console.WriteLine($" - {error}"); + } + } +} +else +{ + Console.WriteLine($"{nameof(Widget)} '{widget}' is valid!"); +} + +class Widget +{ + [Required, MinLength(3)] + public string Name { get; set; } + + public override string ToString() => Name; +} +``` +``` console +❯ widget.exe +Widget has errors! +Name: + - The Name field is required. + +❯ widget.exe Ok +Widget has errors! + Name: + - The field Name must be a string or array type with a minimum length of '3'. + +❯ widget.exe MinimalValidation +Widget 'MinimalValidation' is valid! +``` + +### Web app (.NET 6) +```csharp +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseDeveloperExceptionPage(); +} + +app.MapGet("/", () => "Hello World"); + +app.MapGet("/widgets", () => + new[] { + new Widget { Name = "Shinerizer" }, + new Widget { Name = "Sparklizer" } + }); + +app.MapGet("/widgets/{name}", (string name) => + new Widget { Name = name }); + +app.MapPost("/widgets", (Widget widget) => + !MinimalValidation.TryValidate(widget, out var errors) + ? Results.BadRequest(errors) + : Results.Created($"/widgets/{widget.Name}", widget)); + +app.Run(); + +class Widget +{ + [Required, MinLength(3)] + public string? Name { get; set; } + + public override string? ToString() => Name; +} +``` \ No newline at end of file diff --git a/samples/Samples.Console/Program.cs b/samples/Samples.Console/Program.cs new file mode 100644 index 0000000..eaee2a8 --- /dev/null +++ b/samples/Samples.Console/Program.cs @@ -0,0 +1,30 @@ +using System; +using System.ComponentModel.DataAnnotations; + +var title = args.Length > 0 ? args[0] : ""; +var widget = new Widget { Name = title }; + +if (!MinimalValidation.TryValidate(widget, out var errors)) +{ + Console.WriteLine($"{nameof(Widget)} has errors!"); + foreach (var entry in errors) + { + Console.WriteLine($" {entry.Key}:"); + foreach (var error in entry.Value) + { + Console.WriteLine($" - {error}"); + } + } +} +else +{ + Console.WriteLine($"{nameof(Widget)} '{widget}' is valid!"); +} + +class Widget +{ + [Required, MinLength(3)] + public string Name { get; set; } + + public override string ToString() => Name; +} \ No newline at end of file diff --git a/samples/Samples.Console/Samples.Console.csproj b/samples/Samples.Console/Samples.Console.csproj new file mode 100644 index 0000000..0836020 --- /dev/null +++ b/samples/Samples.Console/Samples.Console.csproj @@ -0,0 +1,12 @@ + + + + Exe + net5.0 + + + + + + + diff --git a/samples/Samples.Web/Program.cs b/samples/Samples.Web/Program.cs new file mode 100644 index 0000000..e8c7828 --- /dev/null +++ b/samples/Samples.Web/Program.cs @@ -0,0 +1,38 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; + +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseDeveloperExceptionPage(); +} + +app.MapGet("/", () => "Hello World"); + +app.MapGet("/widgets", () => + new[] { + new Widget { Name = "Shinerizer" }, + new Widget { Name = "Sparklizer" } + }); + +app.MapGet("/widgets/{name}", (string name) => + new Widget { Name = name }); + +app.MapPost("/widgets", (Widget widget) => + !MinimalValidation.TryValidate(widget, out var errors) + ? Results.BadRequest(errors) + : Results.Created($"/widgets/{widget.Name}", widget)); + +app.Run(); + +class Widget +{ + [Required, MinLength(3)] + public string? Name { get; set; } + + public override string? ToString() => Name; +} diff --git a/samples/Samples.Web/Properties/launchSettings.json b/samples/Samples.Web/Properties/launchSettings.json new file mode 100644 index 0000000..55c3a89 --- /dev/null +++ b/samples/Samples.Web/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:34530", + "sslPort": 44395 + } + }, + "profiles": { + "Samples.Web": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/Samples.Web/Samples.Web.csproj b/samples/Samples.Web/Samples.Web.csproj new file mode 100644 index 0000000..cb02383 --- /dev/null +++ b/samples/Samples.Web/Samples.Web.csproj @@ -0,0 +1,12 @@ + + + + net6.0 + enable + + + + + + + diff --git a/samples/Samples.Web/appsettings.Development.json b/samples/Samples.Web/appsettings.Development.json new file mode 100644 index 0000000..8983e0f --- /dev/null +++ b/samples/Samples.Web/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/samples/Samples.Web/appsettings.json b/samples/Samples.Web/appsettings.json new file mode 100644 index 0000000..d9d9a9b --- /dev/null +++ b/samples/Samples.Web/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/src/MinimalValidation/MinimalValidation.cs b/src/MinimalValidation/MinimalValidation.cs new file mode 100644 index 0000000..0e522ba --- /dev/null +++ b/src/MinimalValidation/MinimalValidation.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace System.ComponentModel.DataAnnotations +{ + public static class MinimalValidation + { + public static bool TryValidate(T target, out IDictionary errors) where T : class + { + return TryValidate(target, recurse: true, out errors); + } + + public static bool TryValidate(T target, bool recurse, out IDictionary errors) where T : class + { + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + var validatedObjects = new Dictionary(); + errors = new Dictionary(); + var isValid = TryValidateImpl(target, recurse, errors, validatedObjects); + + return isValid; + } + + private static int _maxDepth = 3; // Who'd ever need more than 3 + private static ConcurrentDictionary _typeCache = new(); + + private static bool TryValidateImpl(object target, bool recurse, IDictionary errors, Dictionary validatedObjects, string prefix = "", int currentDepth = 0) + { + if (validatedObjects.ContainsKey(target)) + { + var result = validatedObjects[target]; + return !result.HasValue || result == true; + } + + validatedObjects.Add(target, null); + + var validationContext = new ValidationContext(target); + var validationResults = new List(); + + // Validate the simple properties on the target first (Validator.TryValidateObject is non-recursive) + var isValid = Validator.TryValidateObject(target, validationContext, validationResults, validateAllProperties: true); + + var errorsList = new Dictionary>(); + foreach (var result in validationResults) + { + foreach (var name in result.MemberNames) + { + List fieldErrors; + if (errorsList.ContainsKey(name)) + { + fieldErrors = errorsList[name]; + } + else + { + fieldErrors = new List(); + errorsList.Add(name, fieldErrors); + } + if (!string.IsNullOrEmpty(result.ErrorMessage)) + { + fieldErrors.Add(result.ErrorMessage); + } + } + } + + foreach (var error in errorsList) + { + errors.Add($"{prefix}{error.Key}", error.Value.ToArray()); + } + + if (recurse && isValid && currentDepth < _maxDepth) + { + // Validate complex properties + var complexProperties = _typeCache.GetOrAdd(target.GetType(), t => + t.GetProperties().Where(p => IsComplexType(p.PropertyType)).ToArray()); + + foreach (var property in complexProperties) + { + var propertyName = property.Name; + var propertyType = property.PropertyType; + + if (property.GetIndexParameters().Length == 0) + { + var propertyValue = property.GetValue(target); + if (propertyValue != null) + { + isValid = TryValidateImpl(propertyValue, recurse, errors, validatedObjects, prefix: $"{propertyName}.", currentDepth + 1); + } + + if (!isValid) + { + break; + } + } + + if (typeof(IEnumerable).IsAssignableFrom(propertyType)) + { + // Validate each instance in the collection + if (property.GetValue(target) is IEnumerable items) + { + var index = 0; + foreach (var item in items) + { + if (item is not object) continue; + + var itemPrefix = $"{propertyName}[{index}]."; + isValid = TryValidateImpl(item, recurse, errors, validatedObjects, prefix: itemPrefix, currentDepth + 1); + + if (!isValid) + { + break; + } + index++; + } + } + } + } + } + + validatedObjects[target] = isValid; + + return isValid; + } + + private static bool IsComplexType(Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + // Nullable type, check if the nested type is complex + return IsComplexType(type.GetGenericArguments()[0]); + } + + return !(type.IsPrimitive + || type.IsEnum + || type.Equals(typeof(string)) + || type.Equals(typeof(decimal))); + } + } +} diff --git a/src/MinimalValidation/MinimalValidation.csproj b/src/MinimalValidation/MinimalValidation.csproj new file mode 100644 index 0000000..8fb5ece --- /dev/null +++ b/src/MinimalValidation/MinimalValidation.csproj @@ -0,0 +1,24 @@ + + + + A minimal validation library built atop the existing features in .NET's `System.ComponentModel.DataAnnotations` namespace. + Damian Edwards + 0.1.0 + pre + pre-$(BuildNumber) + netstandard2.0;netcoreapp3.1 + Copyright © Damian Edwards + MIT + https://github.com/DamianEdwards/MinimalValidation + https://github.com/DamianEdwards/MinimalValidation + git + ComponentModel, DataAnnotations, validation + 9.0 + enable + + + + + + +