├── .github └── workflows │ └── dotnetcore.yml ├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md └── src ├── Samples └── ConsoleApp │ ├── ConsoleApp.csproj │ └── Program.cs └── Validatum ├── src ├── BrokenRule.cs ├── Extensions │ ├── ExpressionExtensions.cs │ ├── ValidatorBuilderExtensions.Boolean.cs │ ├── ValidatorBuilderExtensions.Collections.cs │ ├── ValidatorBuilderExtensions.Common.cs │ ├── ValidatorBuilderExtensions.Comparison.cs │ ├── ValidatorBuilderExtensions.Strings.cs │ └── ValidatorBuilderExtensions.cs ├── IValidatorBuilder.cs ├── ValidationContext.cs ├── ValidationException.cs ├── ValidationOptions.cs ├── ValidationResult.cs ├── Validator.cs ├── ValidatorBuilder.cs ├── ValidatorDelegate.cs └── Validatum.csproj └── test ├── TestClasses.cs ├── ValidatorBuilderExtensions.Boolean.Tests.cs ├── ValidatorBuilderExtensions.Collections.Tests.cs ├── ValidatorBuilderExtensions.Common.Tests.cs ├── ValidatorBuilderExtensions.Comparison.Tests.cs ├── ValidatorBuilderExtensions.Strings.Tests.cs ├── ValidatorBuilderExtensions.Tests.cs ├── ValidatorBuilderTests.cs └── Validatum.Tests.csproj /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 3.1.101 19 | - name: Install dependencies 20 | run: dotnet restore src/Validatum/test/Validatum.Tests.csproj 21 | - name: Build Validatum 22 | run: dotnet build src/Validatum/test/Validatum.Tests.csproj --configuration Release --no-restore 23 | - name: Test Validatum 24 | run: dotnet test src/Validatum/test/Validatum.Tests.csproj --no-restore --verbosity quiet 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUnit 46 | *.VisualState.xml 47 | TestResult.xml 48 | nunit-*.xml 49 | 50 | # Build Results of an ATL Project 51 | [Dd]ebugPS/ 52 | [Rr]eleasePS/ 53 | dlldata.c 54 | 55 | # Benchmark Results 56 | BenchmarkDotNet.Artifacts/ 57 | 58 | # .NET Core 59 | project.lock.json 60 | project.fragment.lock.json 61 | artifacts/ 62 | 63 | # StyleCop 64 | StyleCopReport.xml 65 | 66 | # Files built by Visual Studio 67 | *_i.c 68 | *_p.c 69 | *_h.h 70 | *.ilk 71 | *.meta 72 | *.obj 73 | *.iobj 74 | *.pch 75 | *.pdb 76 | *.ipdb 77 | *.pgc 78 | *.pgd 79 | *.rsp 80 | *.sbr 81 | *.tlb 82 | *.tli 83 | *.tlh 84 | *.tmp 85 | *.tmp_proj 86 | *_wpftmp.csproj 87 | *.log 88 | *.vspscc 89 | *.vssscc 90 | .builds 91 | *.pidb 92 | *.svclog 93 | *.scc 94 | 95 | # Chutzpah Test files 96 | _Chutzpah* 97 | 98 | # Visual C++ cache files 99 | ipch/ 100 | *.aps 101 | *.ncb 102 | *.opendb 103 | *.opensdf 104 | *.sdf 105 | *.cachefile 106 | *.VC.db 107 | *.VC.VC.opendb 108 | 109 | # Visual Studio profiler 110 | *.psess 111 | *.vsp 112 | *.vspx 113 | *.sap 114 | 115 | # Visual Studio Trace Files 116 | *.e2e 117 | 118 | # TFS 2012 Local Workspace 119 | $tf/ 120 | 121 | # Guidance Automation Toolkit 122 | *.gpState 123 | 124 | # ReSharper is a .NET coding add-in 125 | _ReSharper*/ 126 | *.[Rr]e[Ss]harper 127 | *.DotSettings.user 128 | 129 | # JustCode is a .NET coding add-in 130 | .JustCode 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | nuget.config 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/src/Validatum/test/bin/Debug/netcoreapp3.1/Validatum.Tests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/src/Validatum/test", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/Validatum/test/Validatum.Tests.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile", 15 | "group": { 16 | "kind": "build", 17 | "isDefault": true 18 | } 19 | }, 20 | { 21 | "label": "test", 22 | "command": "dotnet", 23 | "type": "process", 24 | "args": [ 25 | "test", 26 | "${workspaceFolder}/src/Validatum/test/Validatum.Tests.csproj", 27 | "/property:GenerateFullPaths=true", 28 | "/consoleloggerparameters:NoSummary" 29 | ], 30 | "problemMatcher": "$msCompile", 31 | "group": { 32 | "kind": "test", 33 | "isDefault": true 34 | } 35 | } 36 | ] 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Brad Sheldrick 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Validatum 2 | 3 | Validatum is an open-source library for building fluent validation functions for .NET. 4 | 5 | ## Install 6 | 7 | **.NET CLI** 8 | 9 | ```cmd 10 | dotnet add package Validatum --version 1.1.0 11 | ``` 12 | 13 | **Package Manager** 14 | 15 | ```cmd 16 | Install-Package Validatum -Version 1.1.0 17 | ``` 18 | 19 | ## Platform Support 20 | 21 | - .NET Standard 2.0+ 22 | - .NET Core 2.0+ 23 | - .NET Framework 4.6.1+ 24 | 25 | ## Example 26 | 27 | ```csharp 28 | // build a validator 29 | var validator = new ValidatorBuilder() 30 | .Required(e => e.FirstName) 31 | .Email(e => e.Email) 32 | .For(e => e.LastName, name => 33 | { 34 | name.MinLength(5) 35 | .Equal("Smithers"); 36 | }) 37 | .Build(); 38 | 39 | // validate 40 | var result = validator.Validate( 41 | new Employee 42 | { 43 | LastName = "Simpson", 44 | Email = "homer[at]springfieldnuclear.com" 45 | } 46 | ); 47 | 48 | foreach (var rule in result.BrokenRules) 49 | { 50 | Console.WriteLine($"[{rule.Rule}] {rule.Key}: {rule.Message}"); 51 | } 52 | ``` 53 | 54 | Output 55 | 56 | ```sh 57 | [Required] FirstName: Value is required. 58 | [Email] Email: Value must be a valid email. 59 | [Equal] LastName: Value must equal 'Smithers'. 60 | ``` 61 | 62 | ## Why use Validatum? 63 | 64 | - Does not require inheritance of a base type. 65 | - Define and build functions in the scope that validation will be executed. 66 | - Define very complex validation logic in a single statement. 67 | - Easily add custom validators as inline functions. 68 | - Very small package size ~33KB. 69 | - Simple and easily extensible API. 70 | 71 | ## Documentation 72 | 73 | Please visit https://bsheldrick.github.io/validatum 74 | -------------------------------------------------------------------------------- /src/Samples/ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Exe 9 | netcoreapp3.1 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Samples/ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Validatum; 3 | 4 | namespace ConsoleApp 5 | { 6 | class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | var validator = new ValidatorBuilder() 11 | .Required(e => e.FirstName) 12 | .For(e => e.LastName, name => 13 | { 14 | name.Required() 15 | .MaxLength(30); 16 | }) 17 | .Email(e => e.Email) 18 | .Contains(e => e.Skills, "Cromulent") 19 | .Range(e => e.Salary, 50000, 100000) 20 | .LessThanOrEqual(e => e.Commenced, DateTime.Today) 21 | .Continue(v => 22 | { 23 | v.True(e => e.Active); 24 | }) 25 | .Build(); 26 | 27 | var employee = new Employee 28 | { 29 | FirstName = "Homer", 30 | Email = "homer[at]springfieldnuclear.com", 31 | Salary = 45000, 32 | Skills = new[] { "Embiggening" } 33 | }; 34 | 35 | var result = validator.Validate(employee); 36 | 37 | if (!result.IsValid) 38 | { 39 | foreach (var rule in result.BrokenRules) 40 | { 41 | Console.WriteLine($"[{rule.Rule}] {rule.Key}: {rule.Message}"); 42 | } 43 | }; 44 | } 45 | 46 | public class Employee 47 | { 48 | public string FirstName { get; set; } 49 | public string LastName { get; set; } 50 | public string Email { get; set; } 51 | public string Phone { get; set; } 52 | public string[] Skills { get; set; } 53 | public decimal Salary { get; set; } 54 | public DateTime Commenced { get; set; } 55 | public bool Active { get; set; } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Validatum/src/BrokenRule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Validatum 4 | { 5 | /// 6 | /// Represents a broken validation rule. 7 | /// 8 | public class BrokenRule 9 | { 10 | /// 11 | /// Creates a new instance of BrokenRule. 12 | /// 13 | /// The name of the broken rule. 14 | /// The key. 15 | /// The validation message. 16 | public BrokenRule(string rule, string key, string message) 17 | { 18 | if (string.IsNullOrWhiteSpace(rule)) 19 | { 20 | throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(rule)); 21 | } 22 | 23 | Rule = rule; 24 | Key = key; 25 | Message = message; 26 | } 27 | 28 | /// 29 | /// Gets the broken rule name. 30 | /// 31 | public string Rule { get; } 32 | 33 | /// 34 | /// Gets the key. 35 | /// 36 | public string Key { get; } 37 | 38 | /// 39 | /// Gets the message. 40 | /// 41 | public string Message { get; } 42 | 43 | /// 44 | public override string ToString() 45 | => $"[{Rule}] {Key}: {Message}"; 46 | } 47 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | 5 | namespace Validatum 6 | { 7 | /// 8 | /// Extension methods for Expression functions. 9 | /// 10 | public static class ExpressionExtensions 11 | { 12 | /// 13 | /// Gets the path of the given selector expression. 14 | /// 15 | /// The expression. 16 | /// The source type. 17 | /// The target type. 18 | public static string GetPropertyPath(this Expression> expression) 19 | { 20 | MemberExpression memberExpression = null; 21 | 22 | // first try extract member expression from unary type 23 | if (expression.Body.NodeType == ExpressionType.Convert) 24 | { 25 | if (expression.Body is UnaryExpression unary) 26 | { 27 | memberExpression = unary.Operand as MemberExpression; 28 | } 29 | } 30 | 31 | // try a straight cast of the body 32 | if (memberExpression is null) 33 | { 34 | memberExpression = expression.Body as MemberExpression; 35 | } 36 | 37 | // still null throw exception 38 | if (memberExpression is null) 39 | { 40 | throw new NotSupportedException("Expression should be in format x => x.Property."); 41 | } 42 | 43 | return GetMemberPath(memberExpression); 44 | } 45 | 46 | private static string GetMemberPath(MemberExpression expression) 47 | { 48 | if (expression is null) 49 | { 50 | throw new ArgumentNullException(nameof(expression)); 51 | } 52 | 53 | var parts = new List(); 54 | 55 | while (!(expression is null)) 56 | { 57 | parts.Add(expression.Member.Name); 58 | expression = expression.Expression as MemberExpression; 59 | } 60 | 61 | parts.Reverse(); 62 | 63 | return string.Join(".", parts); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.Boolean.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace Validatum 5 | { 6 | public static partial class ValidatorBuilderExtensions 7 | { 8 | /// 9 | /// Adds a validator to ensure the value is true. 10 | /// 11 | /// The validator builder. 12 | /// The key to use in broken rule. 13 | /// The message to use in broken rule. 14 | public static IValidatorBuilder True(this IValidatorBuilder builder, string key = null, string message = null) 15 | { 16 | if (builder is null) 17 | { 18 | throw new ArgumentNullException(nameof(builder)); 19 | } 20 | 21 | return builder 22 | .WhenNot( 23 | ctx => ctx.Value, 24 | ctx => ctx.AddBrokenRule(nameof(True), key, message ?? "Value must be true.") 25 | ); 26 | } 27 | 28 | /// 29 | /// Adds a validator to ensure the value is true for the target of the selector expression. 30 | /// 31 | /// The validator builder. 32 | /// The selector expression. 33 | /// The key to use in broken rule. 34 | /// The message to use in broken rule. 35 | /// The source type. 36 | public static IValidatorBuilder True(this IValidatorBuilder builder, 37 | Expression> selector, 38 | string key = null, 39 | string message = null) 40 | { 41 | if (builder is null) 42 | { 43 | throw new ArgumentNullException(nameof(builder)); 44 | } 45 | 46 | if (selector is null) 47 | { 48 | throw new ArgumentNullException(nameof(selector)); 49 | } 50 | 51 | key = key ?? selector.GetPropertyPath(); 52 | 53 | return builder.For(selector, p => p.True(key, message)); 54 | } 55 | 56 | /// 57 | /// Adds a validator to ensure the value is false. 58 | /// 59 | /// The validator builder. 60 | /// The key to use in broken rule. 61 | /// The message to use in broken rule. 62 | public static IValidatorBuilder False(this IValidatorBuilder builder, string key = null, string message = null) 63 | { 64 | if (builder is null) 65 | { 66 | throw new ArgumentNullException(nameof(builder)); 67 | } 68 | 69 | return builder 70 | .When( 71 | ctx => ctx.Value, 72 | ctx => ctx.AddBrokenRule(nameof(False), key, message ?? "Value must be false.") 73 | ); 74 | } 75 | 76 | /// 77 | /// Adds a validator to ensure the value is false for the target of the selector expression. 78 | /// 79 | /// The validator builder. 80 | /// The selector expression. 81 | /// The key to use in broken rule. 82 | /// The message to use in broken rule. 83 | /// The source type. 84 | public static IValidatorBuilder False(this IValidatorBuilder builder, 85 | Expression> selector, 86 | string key = null, 87 | string message = null) 88 | { 89 | if (builder is null) 90 | { 91 | throw new ArgumentNullException(nameof(builder)); 92 | } 93 | 94 | if (selector is null) 95 | { 96 | throw new ArgumentNullException(nameof(selector)); 97 | } 98 | 99 | key = key ?? selector.GetPropertyPath(); 100 | 101 | return builder.For(selector, p => p.False(key, message)); 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.Collections.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | 6 | namespace Validatum 7 | { 8 | public static partial class ValidatorBuilderExtensions 9 | { 10 | /// 11 | /// Adds a validator to ensure a collection has a specified item count. 12 | /// 13 | /// The validator builder. 14 | /// The item count. 15 | /// The key to use in broken rule. 16 | /// The message to use in broken rule. 17 | public static IValidatorBuilder> Count(this IValidatorBuilder> builder, int count, string key = null, string message = null) 18 | { 19 | if (builder is null) 20 | { 21 | throw new ArgumentNullException(nameof(builder)); 22 | } 23 | 24 | if (count < 0) 25 | { 26 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 27 | } 28 | 29 | return builder 30 | .WhenNot( 31 | ctx => ctx.Value.Count() == count, 32 | ctx => ctx.AddBrokenRule(nameof(Count), key ?? $"IEnumerable<{typeof(T).Name}>", message ?? $"Collection count must equal {count}.") 33 | ); 34 | } 35 | 36 | /// 37 | /// Adds a validator to ensure a collection has a specified item count for the target of the selector expression. 38 | /// 39 | /// The validator builder. 40 | /// The selector expression. 41 | /// The item count. 42 | /// The key to use in broken rule. 43 | /// The message to use in broken rule. 44 | public static IValidatorBuilder Count(this IValidatorBuilder builder, 45 | Expression>> selector, 46 | int count, 47 | string key = null, 48 | string message = null) 49 | { 50 | if (builder is null) 51 | { 52 | throw new ArgumentNullException(nameof(builder)); 53 | } 54 | 55 | if (selector is null) 56 | { 57 | throw new ArgumentNullException(nameof(selector)); 58 | } 59 | 60 | if (count < 0) 61 | { 62 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 63 | } 64 | 65 | key = key ?? selector.GetPropertyPath(); 66 | 67 | return builder.For>(selector, p => p.Count(count, key, message)); 68 | } 69 | 70 | /// 71 | /// Adds a validator to ensure a collection has a specified minimum item count. 72 | /// 73 | /// The validator builder. 74 | /// The minimum item count. 75 | /// The key to use in broken rule. 76 | /// The message to use in broken rule. 77 | public static IValidatorBuilder> MinCount(this IValidatorBuilder> builder, int count, string key = null, string message = null) 78 | { 79 | if (builder is null) 80 | { 81 | throw new ArgumentNullException(nameof(builder)); 82 | } 83 | 84 | if (count < 0) 85 | { 86 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 87 | } 88 | 89 | return builder 90 | .When( 91 | ctx => ctx.Value.Count() < count, 92 | ctx => ctx.AddBrokenRule(nameof(MinCount), key ?? $"IEnumerable<{typeof(T).Name}>", message ?? $"Collection count must be at least {count}.") 93 | ); 94 | } 95 | 96 | /// 97 | /// Adds a validator to ensure a collection has a specified minimum item count for the target of the selector expression. 98 | /// 99 | /// The validator builder. 100 | /// The selector expression. 101 | /// The minimum item count. 102 | /// The key to use in broken rule. 103 | /// The message to use in broken rule. 104 | public static IValidatorBuilder MinCount(this IValidatorBuilder builder, 105 | Expression>> selector, 106 | int count, 107 | string key = null, 108 | string message = null) 109 | { 110 | if (builder is null) 111 | { 112 | throw new ArgumentNullException(nameof(builder)); 113 | } 114 | 115 | if (selector is null) 116 | { 117 | throw new ArgumentNullException(nameof(selector)); 118 | } 119 | 120 | if (count < 0) 121 | { 122 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 123 | } 124 | 125 | key = key ?? selector.GetPropertyPath(); 126 | 127 | return builder.For>(selector, p => p.MinCount(count, key, message)); 128 | } 129 | 130 | /// 131 | /// Adds a validator to ensure a collection has a specified maximum item count. 132 | /// 133 | /// The validator builder. 134 | /// The maximum item count. 135 | /// The key to use in broken rule. 136 | /// The message to use in broken rule. 137 | public static IValidatorBuilder> MaxCount(this IValidatorBuilder> builder, int count, string key = null, string message = null) 138 | { 139 | if (builder is null) 140 | { 141 | throw new ArgumentNullException(nameof(builder)); 142 | } 143 | 144 | if (count < 0) 145 | { 146 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 147 | } 148 | 149 | return builder 150 | .When( 151 | ctx => ctx.Value.Count() > count, 152 | ctx => ctx.AddBrokenRule(nameof(MaxCount), key ?? $"IEnumerable<{typeof(T).Name}>", message ?? $"Collection count cannot be greater than {count}.") 153 | ); 154 | } 155 | 156 | /// 157 | /// Adds a validator to ensure a collection has a specified maximum item count for the target of the selector expression. 158 | /// 159 | /// The validator builder. 160 | /// The selector expression. 161 | /// The maximum item count. 162 | /// The key to use in broken rule. 163 | /// The message to use in broken rule. 164 | public static IValidatorBuilder MaxCount(this IValidatorBuilder builder, 165 | Expression>> selector, 166 | int count, 167 | string key = null, 168 | string message = null) 169 | { 170 | if (builder is null) 171 | { 172 | throw new ArgumentNullException(nameof(builder)); 173 | } 174 | 175 | if (selector is null) 176 | { 177 | throw new ArgumentNullException(nameof(selector)); 178 | } 179 | 180 | if (count < 0) 181 | { 182 | throw new ArgumentOutOfRangeException(nameof(count), count, "Cannot be less than zero"); 183 | } 184 | 185 | key = key ?? selector.GetPropertyPath(); 186 | 187 | return builder.For>(selector, p => p.MaxCount(count, key, message)); 188 | } 189 | 190 | /// 191 | /// Adds a validator to ensure a collection contains a specified item. 192 | /// 193 | /// The validator builder. 194 | /// The item. 195 | /// The key to use in broken rule. 196 | /// The message to use in broken rule. 197 | public static IValidatorBuilder> Contains(this IValidatorBuilder> builder, T item, string key = null, string message = null) 198 | { 199 | if (builder is null) 200 | { 201 | throw new ArgumentNullException(nameof(builder)); 202 | } 203 | 204 | if (item is null) 205 | { 206 | throw new ArgumentNullException(nameof(item)); 207 | } 208 | 209 | return builder 210 | .WhenNot( 211 | ctx => ctx.Value?.Contains(item) ?? false, 212 | ctx => ctx.AddBrokenRule(nameof(Contains), key ?? $"IEnumerable<{typeof(T).Name}>", message ?? $"Collection must contain item '{item.ToString()}'.") 213 | ); 214 | } 215 | 216 | /// 217 | /// Adds a validator to ensure a collection has a specified item for the target of the selector expression. 218 | /// 219 | /// The validator builder. 220 | /// The selector expression. 221 | /// The item. 222 | /// The key to use in broken rule. 223 | /// The message to use in broken rule. 224 | public static IValidatorBuilder Contains(this IValidatorBuilder builder, 225 | Expression>> selector, 226 | P item, 227 | string key = null, 228 | string message = null) 229 | { 230 | if (builder is null) 231 | { 232 | throw new ArgumentNullException(nameof(builder)); 233 | } 234 | 235 | if (selector is null) 236 | { 237 | throw new ArgumentNullException(nameof(selector)); 238 | } 239 | 240 | if (item is null) 241 | { 242 | throw new ArgumentNullException(nameof(item)); 243 | } 244 | 245 | key = key ?? selector.GetPropertyPath(); 246 | 247 | return builder.For>(selector, p => p.Contains(item, key, message)); 248 | } 249 | } 250 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.Common.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace Validatum 5 | { 6 | public static partial class ValidatorBuilderExtensions 7 | { 8 | /// 9 | /// Adds a validator to ensure the value is not null. 10 | /// 11 | /// The validator builder. 12 | /// The key to use in broken rule. 13 | /// The message to use in broken rule. 14 | public static IValidatorBuilder NotNull(this IValidatorBuilder builder, string key = null, string message = null) 15 | where T : class 16 | { 17 | if (builder is null) 18 | { 19 | throw new ArgumentNullException(nameof(builder)); 20 | } 21 | 22 | return builder 23 | .When( 24 | ctx => ctx.Value is null, 25 | ctx => ctx.AddBrokenRule(nameof(NotNull), key, message ?? "Value cannot be null.") 26 | ); 27 | } 28 | 29 | /// 30 | /// Adds a validator to ensure the value is not null for the target of the selector expression. 31 | /// 32 | /// The validator builder. 33 | /// The selector expression. 34 | /// The key to use in broken rule. 35 | /// The message to use in broken rule. 36 | /// The source type. 37 | /// The target type. 38 | public static IValidatorBuilder NotNull(this IValidatorBuilder builder, 39 | Expression> selector, 40 | string key = null, 41 | string message = null) 42 | where P : class 43 | { 44 | if (builder is null) 45 | { 46 | throw new ArgumentNullException(nameof(builder)); 47 | } 48 | 49 | if (selector is null) 50 | { 51 | throw new ArgumentNullException(nameof(selector)); 52 | } 53 | 54 | key = key ?? selector.GetPropertyPath(); 55 | 56 | return builder.For(selector, p => p.NotNull(key, message)); 57 | } 58 | 59 | /// 60 | /// Adds a validator to ensure the value is null. 61 | /// 62 | /// The validator builder. 63 | /// The key to use in broken rule. 64 | /// The message to use in broken rule. 65 | public static IValidatorBuilder Null(this IValidatorBuilder builder, string key = null, string message = null) 66 | where T : class 67 | { 68 | if (builder is null) 69 | { 70 | throw new ArgumentNullException(nameof(builder)); 71 | } 72 | 73 | return builder 74 | .WhenNot( 75 | ctx => ctx.Value is null, 76 | ctx => ctx.AddBrokenRule(nameof(Null), key, message ?? "Value must be null.") 77 | ); 78 | } 79 | 80 | /// 81 | /// Adds a validator to ensure the value is null for the target of the selector expression. 82 | /// 83 | /// The validator builder. 84 | /// The selector expression. 85 | /// The key to use in broken rule. 86 | /// The message to use in broken rule. 87 | /// The source type. 88 | /// The target type. 89 | public static IValidatorBuilder Null(this IValidatorBuilder builder, 90 | Expression> selector, 91 | string key = null, 92 | string message = null) 93 | where P : class 94 | { 95 | if (builder is null) 96 | { 97 | throw new ArgumentNullException(nameof(builder)); 98 | } 99 | 100 | if (selector is null) 101 | { 102 | throw new ArgumentNullException(nameof(selector)); 103 | } 104 | 105 | key = key ?? selector.GetPropertyPath(); 106 | 107 | return builder.For(selector, p => p.Null(key, message)); 108 | } 109 | 110 | /// 111 | /// Adds a validator to ensure the value is equal to a specified value. 112 | /// 113 | /// The validator builder. 114 | /// The value to test equality. 115 | /// The key to use in broken rule. 116 | /// The message to use in broken rule. 117 | public static IValidatorBuilder Equal(this IValidatorBuilder builder, T other, string key = null, string message = null) 118 | where T : IEquatable 119 | { 120 | if (builder is null) 121 | { 122 | throw new ArgumentNullException(nameof(builder)); 123 | } 124 | 125 | return builder 126 | .WhenNot( 127 | ctx => (ctx.Value is null && other is null) || (ctx.Value?.Equals(other) ?? false), 128 | ctx => ctx.AddBrokenRule(nameof(Equal), key, message ?? $"Value must equal '{other?.ToString() ?? "null"}'.") 129 | ); 130 | } 131 | 132 | /// 133 | /// Adds a validator to ensure the value is equal to a specified value for the target of the selector expression. 134 | /// 135 | /// The validator builder. 136 | /// The selector expression. 137 | /// The value to test equality. 138 | /// The key to use in broken rule. 139 | /// The message to use in broken rule. 140 | /// The source type. 141 | /// The target type. 142 | public static IValidatorBuilder Equal(this IValidatorBuilder builder, 143 | Expression> selector, 144 | P other, 145 | string key = null, 146 | string message = null) 147 | where P : IEquatable

148 | { 149 | if (builder is null) 150 | { 151 | throw new ArgumentNullException(nameof(builder)); 152 | } 153 | 154 | if (selector is null) 155 | { 156 | throw new ArgumentNullException(nameof(selector)); 157 | } 158 | 159 | key = key ?? selector.GetPropertyPath(); 160 | 161 | return builder.For(selector, p => p.Equal(other, key, message)); 162 | } 163 | 164 | ///

165 | /// Adds a validator to ensure the value is not equal to a specified value. 166 | /// 167 | /// The validator builder. 168 | /// The value to test equality. 169 | /// The key to use in broken rule. 170 | /// The message to use in broken rule. 171 | public static IValidatorBuilder NotEqual(this IValidatorBuilder builder, T other, string key = null, string message = null) 172 | where T : IEquatable 173 | { 174 | if (builder is null) 175 | { 176 | throw new ArgumentNullException(nameof(builder)); 177 | } 178 | 179 | return builder 180 | .When( 181 | ctx => (ctx.Value is null && other is null) || (ctx.Value?.Equals(other) ?? false), 182 | ctx => ctx.AddBrokenRule(nameof(NotEqual), key, message ?? $"Value must not equal '{other?.ToString() ?? "null"}'.") 183 | ); 184 | } 185 | 186 | /// 187 | /// Adds a validator to ensure the value is not equal to a specified value for the target of the selector expression. 188 | /// 189 | /// The validator builder. 190 | /// The selector expression. 191 | /// The value to test equality. 192 | /// The key to use in broken rule. 193 | /// The message to use in broken rule. 194 | /// The source type. 195 | /// The target type. 196 | public static IValidatorBuilder NotEqual(this IValidatorBuilder builder, 197 | Expression> selector, 198 | P other, 199 | string key = null, 200 | string message = null) 201 | where P : IEquatable

202 | { 203 | if (builder is null) 204 | { 205 | throw new ArgumentNullException(nameof(builder)); 206 | } 207 | 208 | if (selector is null) 209 | { 210 | throw new ArgumentNullException(nameof(selector)); 211 | } 212 | 213 | key = key ?? selector.GetPropertyPath(); 214 | 215 | return builder.For(selector, p => p.NotEqual(other, key, message)); 216 | } 217 | } 218 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.Comparison.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | 4 | namespace Validatum 5 | { 6 | public static partial class ValidatorBuilderExtensions 7 | { 8 | ///

9 | /// Adds a validator to ensure the value is greater than a specified value. 10 | /// 11 | /// The validator builder. 12 | /// The value to test if greater than. 13 | /// The key to use in broken rule. 14 | /// The message to use in broken rule. 15 | public static IValidatorBuilder GreaterThan(this IValidatorBuilder builder, T other, string key = null, string message = null) 16 | where T : IComparable 17 | { 18 | if (builder is null) 19 | { 20 | throw new ArgumentNullException(nameof(builder)); 21 | } 22 | 23 | return builder 24 | .WhenNot( 25 | ctx => ctx.Value?.CompareTo(other) > 0, 26 | ctx => ctx.AddBrokenRule(nameof(GreaterThan), key, message ?? $"Value must be greater than '{other?.ToString() ?? "null"}'.") 27 | ); 28 | } 29 | 30 | /// 31 | /// Adds a validator to ensure the value is greater than a specified value for the target of the selector expression. 32 | /// 33 | /// The validator builder. 34 | /// The selector expression. 35 | /// The value to test if greater than. 36 | /// The key to use in broken rule. 37 | /// The message to use in broken rule. 38 | public static IValidatorBuilder GreaterThan(this IValidatorBuilder builder, 39 | Expression> selector, 40 | P other, 41 | string key = null, 42 | string message = null) 43 | where P : IComparable 44 | { 45 | if (builder is null) 46 | { 47 | throw new ArgumentNullException(nameof(builder)); 48 | } 49 | 50 | if (selector is null) 51 | { 52 | throw new ArgumentNullException(nameof(selector)); 53 | } 54 | 55 | key = key ?? selector.GetPropertyPath(); 56 | 57 | return builder.For(selector, p => p.GreaterThan(other, key, message)); 58 | } 59 | 60 | /// 61 | /// Adds a validator to ensure the value is greater than or equal to a specified value. 62 | /// 63 | /// The validator builder. 64 | /// The value to test if greater than or equal. 65 | /// The key to use in broken rule. 66 | /// The message to use in broken rule. 67 | public static IValidatorBuilder GreaterThanOrEqual(this IValidatorBuilder builder, T other, string key = null, string message = null) 68 | where T : IComparable 69 | { 70 | if (builder is null) 71 | { 72 | throw new ArgumentNullException(nameof(builder)); 73 | } 74 | 75 | return builder 76 | .WhenNot( 77 | ctx => ctx.Value?.CompareTo(other) >= 0, 78 | ctx => ctx.AddBrokenRule(nameof(GreaterThanOrEqual), key, message ?? $"Value must be greater than or equal to '{other?.ToString() ?? "null"}'.") 79 | ); 80 | } 81 | 82 | /// 83 | /// Adds a validator to ensure the value is greater than or equal to a specified value 84 | /// for the target of the selector expression. 85 | /// 86 | /// The validator builder. 87 | /// The selector expression. 88 | /// The value to test if greater than. 89 | /// The key to use in broken rule. 90 | /// The message to use in broken rule. 91 | public static IValidatorBuilder GreaterThanOrEqual(this IValidatorBuilder builder, 92 | Expression> selector, 93 | P other, 94 | string key = null, 95 | string message = null) 96 | where P : IComparable 97 | { 98 | if (builder is null) 99 | { 100 | throw new ArgumentNullException(nameof(builder)); 101 | } 102 | 103 | if (selector is null) 104 | { 105 | throw new ArgumentNullException(nameof(selector)); 106 | } 107 | 108 | key = key ?? selector.GetPropertyPath(); 109 | 110 | return builder.For(selector, p => p.GreaterThanOrEqual(other, key, message)); 111 | } 112 | 113 | /// 114 | /// Adds a validator to ensure the value is less than a specified value. 115 | /// 116 | /// The validator builder. 117 | /// The value to test if less than. 118 | /// The key to use in broken rule. 119 | /// The message to use in broken rule. 120 | public static IValidatorBuilder LessThan(this IValidatorBuilder builder, T other, string key = null, string message = null) 121 | where T : IComparable 122 | { 123 | if (builder is null) 124 | { 125 | throw new ArgumentNullException(nameof(builder)); 126 | } 127 | 128 | return builder 129 | .WhenNot( 130 | ctx => ctx.Value?.CompareTo(other) < 0, 131 | ctx => ctx.AddBrokenRule(nameof(LessThan), key, message ?? $"Value must be less than '{other?.ToString() ?? "null"}'.") 132 | ); 133 | } 134 | 135 | /// 136 | /// Adds a validator to ensure the value is less than a specified value for the target of the selector expression. 137 | /// 138 | /// The validator builder. 139 | /// The selector expression. 140 | /// The value to test if less than. 141 | /// The key to use in broken rule. 142 | /// The message to use in broken rule. 143 | public static IValidatorBuilder LessThan(this IValidatorBuilder builder, 144 | Expression> selector, 145 | P other, 146 | string key = null, 147 | string message = null) 148 | where P : IComparable 149 | { 150 | if (builder is null) 151 | { 152 | throw new ArgumentNullException(nameof(builder)); 153 | } 154 | 155 | if (selector is null) 156 | { 157 | throw new ArgumentNullException(nameof(selector)); 158 | } 159 | 160 | key = key ?? selector.GetPropertyPath(); 161 | 162 | return builder.For(selector, p => p.LessThan(other, key, message)); 163 | } 164 | 165 | /// 166 | /// Adds a validator to ensure the value is less than or equal to a specified value. 167 | /// 168 | /// The validator builder. 169 | /// The value to test if less than or equal to. 170 | /// The key to use in broken rule. 171 | /// The message to use in broken rule. 172 | public static IValidatorBuilder LessThanOrEqual(this IValidatorBuilder builder, T other, string key = null, string message = null) 173 | where T : IComparable 174 | { 175 | if (builder is null) 176 | { 177 | throw new ArgumentNullException(nameof(builder)); 178 | } 179 | 180 | return builder 181 | .WhenNot( 182 | ctx => ctx.Value?.CompareTo(other) <= 0, 183 | ctx => ctx.AddBrokenRule(nameof(LessThanOrEqual), key, message ?? $"Value must be less than or equal to '{other?.ToString() ?? "null"}'.") 184 | ); 185 | } 186 | 187 | /// 188 | /// Adds a validator to ensure the value is less than or equal to a specified value for the target of the selector expression. 189 | /// 190 | /// The validator builder. 191 | /// The selector expression. 192 | /// The value to test if less than or equal to. 193 | /// The key to use in broken rule. 194 | /// The message to use in broken rule. 195 | public static IValidatorBuilder LessThanOrEqual(this IValidatorBuilder builder, 196 | Expression> selector, 197 | P other, 198 | string key = null, 199 | string message = null) 200 | where P : IComparable 201 | { 202 | if (builder is null) 203 | { 204 | throw new ArgumentNullException(nameof(builder)); 205 | } 206 | 207 | if (selector is null) 208 | { 209 | throw new ArgumentNullException(nameof(selector)); 210 | } 211 | 212 | key = key ?? selector.GetPropertyPath(); 213 | 214 | return builder.For(selector, p => p.LessThanOrEqual(other, key, message)); 215 | } 216 | 217 | /// 218 | /// Adds a validator to ensure the value is within a specified value range. 219 | /// 220 | /// The validator builder. 221 | /// The lower bound range value. 222 | /// The upper bound range value. 223 | /// The key to use in broken rule. 224 | /// The message to use in broken rule. 225 | public static IValidatorBuilder Range(this IValidatorBuilder builder, 226 | T lower, 227 | T upper, 228 | string key = null, 229 | string message = null) 230 | where T : IComparable 231 | { 232 | if (builder is null) 233 | { 234 | throw new ArgumentNullException(nameof(builder)); 235 | } 236 | 237 | if (lower is null) 238 | { 239 | throw new ArgumentNullException(nameof(lower)); 240 | } 241 | 242 | if (upper is null) 243 | { 244 | throw new ArgumentNullException(nameof(upper)); 245 | } 246 | 247 | return builder 248 | .WhenNot( 249 | ctx => ctx.Value != null && (lower.CompareTo(ctx.Value) <= 0 && upper.CompareTo(ctx.Value) >= 0), 250 | ctx => ctx.AddBrokenRule(nameof(Range), key, message ?? $"Value must be in range '{lower.ToString() ?? "null"}' to '{upper.ToString() ?? "null"}'.") 251 | ); 252 | } 253 | 254 | /// 255 | /// Adds a validator to ensure the value is within a specified value range for the target of the selector expression. 256 | /// 257 | /// The validator builder. 258 | /// The selector expression. 259 | /// The lower bound range value. 260 | /// The upper bound range value. 261 | /// The key to use in broken rule. 262 | /// The message to use in broken rule. 263 | public static IValidatorBuilder Range(this IValidatorBuilder builder, 264 | Expression> selector, 265 | P lower, 266 | P upper, 267 | string key = null, 268 | string message = null) 269 | where P : IComparable 270 | { 271 | if (builder is null) 272 | { 273 | throw new ArgumentNullException(nameof(builder)); 274 | } 275 | 276 | if (selector is null) 277 | { 278 | throw new ArgumentNullException(nameof(selector)); 279 | } 280 | 281 | if (lower is null) 282 | { 283 | throw new ArgumentNullException(nameof(lower)); 284 | } 285 | 286 | if (upper is null) 287 | { 288 | throw new ArgumentNullException(nameof(upper)); 289 | } 290 | 291 | key = key ?? selector.GetPropertyPath(); 292 | 293 | return builder.For(selector, p => p.Range(lower, upper, key, message)); 294 | } 295 | 296 | /// 297 | /// Adds a validator to ensure two values from the targets of selector expressions are equal. 298 | /// 299 | /// The validator builder. 300 | /// The left selector expression. 301 | /// The right selector expression. 302 | /// The key to use in broken rule. 303 | /// The message to use in broken rule. 304 | public static IValidatorBuilder Compare(this IValidatorBuilder builder, 305 | Expression> leftSelector, 306 | Expression> rightSelector, 307 | string key = null, 308 | string message = null) 309 | { 310 | if (builder is null) 311 | { 312 | throw new ArgumentNullException(nameof(builder)); 313 | } 314 | 315 | if (leftSelector is null) 316 | { 317 | throw new ArgumentNullException(nameof(leftSelector)); 318 | } 319 | 320 | if (rightSelector is null) 321 | { 322 | throw new ArgumentNullException(nameof(rightSelector)); 323 | } 324 | 325 | var leftFunc = leftSelector.Compile(); 326 | var rightFunc = rightSelector.Compile(); 327 | 328 | var leftKey = leftSelector.GetPropertyPath(); 329 | var rightKey = rightSelector.GetPropertyPath(); 330 | 331 | return builder. 332 | WhenNot( 333 | ctx => leftFunc(ctx.Value)?.Equals(rightFunc(ctx.Value)) ?? false, 334 | ctx => ctx.AddBrokenRule(nameof(Compare), key ?? leftKey, message ?? $"Value must be equal to value of {rightKey}") 335 | ); 336 | } 337 | 338 | /// 339 | /// Adds a validator to ensure the value of the target of the first selector expression 340 | /// is greater than the value of the target of the second selector expression. 341 | /// 342 | /// The validator builder. 343 | /// The left selector expression. 344 | /// The right selector expression. 345 | /// The key to use in broken rule. 346 | /// The message to use in broken rule. 347 | public static IValidatorBuilder CompareGreaterThan(this IValidatorBuilder builder, 348 | Expression> leftSelector, 349 | Expression> rightSelector, 350 | string key = null, 351 | string message = null) 352 | where P : IComparable 353 | { 354 | if (builder is null) 355 | { 356 | throw new ArgumentNullException(nameof(builder)); 357 | } 358 | 359 | if (leftSelector is null) 360 | { 361 | throw new ArgumentNullException(nameof(leftSelector)); 362 | } 363 | 364 | if (rightSelector is null) 365 | { 366 | throw new ArgumentNullException(nameof(rightSelector)); 367 | } 368 | 369 | var leftFunc = leftSelector.Compile(); 370 | var rightFunc = rightSelector.Compile(); 371 | 372 | var leftKey = leftSelector.GetPropertyPath(); 373 | var rightKey = rightSelector.GetPropertyPath(); 374 | 375 | return builder. 376 | WhenNot( 377 | ctx => leftFunc(ctx.Value)?.CompareTo(rightFunc(ctx.Value)) > 0, 378 | ctx => ctx.AddBrokenRule(nameof(Compare), key ?? leftKey, message ?? $"Value must be greater than value of {rightKey}") 379 | ); 380 | } 381 | 382 | /// 383 | /// Adds a validator to ensure the value of the target of the first selector expression 384 | /// is greater than or equal to the value of the target of the second selector expression. 385 | /// 386 | /// The validator builder. 387 | /// The left selector expression. 388 | /// The right selector expression. 389 | /// The key to use in broken rule. 390 | /// The message to use in broken rule. 391 | public static IValidatorBuilder CompareGreaterThanOrEqual(this IValidatorBuilder builder, 392 | Expression> leftSelector, 393 | Expression> rightSelector, 394 | string key = null, 395 | string message = null) 396 | where P : IComparable 397 | { 398 | if (builder is null) 399 | { 400 | throw new ArgumentNullException(nameof(builder)); 401 | } 402 | 403 | if (leftSelector is null) 404 | { 405 | throw new ArgumentNullException(nameof(leftSelector)); 406 | } 407 | 408 | if (rightSelector is null) 409 | { 410 | throw new ArgumentNullException(nameof(rightSelector)); 411 | } 412 | 413 | var leftFunc = leftSelector.Compile(); 414 | var rightFunc = rightSelector.Compile(); 415 | 416 | var leftKey = leftSelector.GetPropertyPath(); 417 | var rightKey = rightSelector.GetPropertyPath(); 418 | 419 | return builder. 420 | WhenNot( 421 | ctx => leftFunc(ctx.Value)?.CompareTo(rightFunc(ctx.Value)) >= 0, 422 | ctx => ctx.AddBrokenRule(nameof(Compare), key ?? leftKey, message ?? $"Value must be greater than or equal to value of {rightKey}") 423 | ); 424 | } 425 | 426 | /// 427 | /// Adds a validator to ensure the value of the target of the first selector expression 428 | /// is less than the value of the target of the second selector expression. 429 | /// 430 | /// The validator builder. 431 | /// The left selector expression. 432 | /// The right selector expression. 433 | /// The key to use in broken rule. 434 | /// The message to use in broken rule. 435 | public static IValidatorBuilder CompareLessThan(this IValidatorBuilder builder, 436 | Expression> leftSelector, 437 | Expression> rightSelector, 438 | string key = null, 439 | string message = null) 440 | where P : IComparable 441 | { 442 | if (builder is null) 443 | { 444 | throw new ArgumentNullException(nameof(builder)); 445 | } 446 | 447 | if (leftSelector is null) 448 | { 449 | throw new ArgumentNullException(nameof(leftSelector)); 450 | } 451 | 452 | if (rightSelector is null) 453 | { 454 | throw new ArgumentNullException(nameof(rightSelector)); 455 | } 456 | 457 | var leftFunc = leftSelector.Compile(); 458 | var rightFunc = rightSelector.Compile(); 459 | 460 | var leftKey = leftSelector.GetPropertyPath(); 461 | var rightKey = rightSelector.GetPropertyPath(); 462 | 463 | return builder. 464 | WhenNot( 465 | ctx => leftFunc(ctx.Value)?.CompareTo(rightFunc(ctx.Value)) < 0, 466 | ctx => ctx.AddBrokenRule(nameof(Compare), key ?? leftKey, message ?? $"Value must be less than value of {rightKey}") 467 | ); 468 | } 469 | 470 | /// 471 | /// Adds a validator to ensure the value of the target of the first selector expression 472 | /// is less than or equal to the value of the target of the second selector expression. 473 | /// 474 | /// The validator builder. 475 | /// The left selector expression. 476 | /// The right selector expression. 477 | /// The key to use in broken rule. 478 | /// The message to use in broken rule. 479 | public static IValidatorBuilder CompareLessThanOrEqual(this IValidatorBuilder builder, 480 | Expression> leftSelector, 481 | Expression> rightSelector, 482 | string key = null, 483 | string message = null) 484 | where P : IComparable 485 | { 486 | if (builder is null) 487 | { 488 | throw new ArgumentNullException(nameof(builder)); 489 | } 490 | 491 | if (leftSelector is null) 492 | { 493 | throw new ArgumentNullException(nameof(leftSelector)); 494 | } 495 | 496 | if (rightSelector is null) 497 | { 498 | throw new ArgumentNullException(nameof(rightSelector)); 499 | } 500 | 501 | var leftFunc = leftSelector.Compile(); 502 | var rightFunc = rightSelector.Compile(); 503 | 504 | var leftKey = leftSelector.GetPropertyPath(); 505 | var rightKey = rightSelector.GetPropertyPath(); 506 | 507 | return builder. 508 | WhenNot( 509 | ctx => leftFunc(ctx.Value)?.CompareTo(rightFunc(ctx.Value)) <= 0, 510 | ctx => ctx.AddBrokenRule(nameof(Compare), key ?? leftKey, message ?? $"Value must be less than or equal to value of {rightKey}") 511 | ); 512 | } 513 | } 514 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.Strings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using System.Text.RegularExpressions; 4 | 5 | namespace Validatum 6 | { 7 | public static partial class ValidatorBuilderExtensions 8 | { 9 | /// 10 | /// Adds a validator to ensure the value is not an empty string. 11 | /// 12 | /// The validation builder. 13 | /// The key to use in broken rule. 14 | /// The message to use in broken rule. 15 | public static IValidatorBuilder NotEmpty(this IValidatorBuilder builder, string key = null, string message = null) 16 | { 17 | if (builder is null) 18 | { 19 | throw new ArgumentNullException(nameof(builder)); 20 | } 21 | 22 | return builder 23 | .When( 24 | ctx => ctx.Value == string.Empty, 25 | ctx => ctx.AddBrokenRule(nameof(NotEmpty), key, message ?? "Value cannot be empty.") 26 | ); 27 | } 28 | 29 | /// 30 | /// Adds a validator to ensure the value is not an empty string for the target of the selector expression. 31 | /// 32 | /// The validation builder. 33 | /// The selector expression. 34 | /// The key to use in broken rule. 35 | /// The message to use in broken rule. 36 | public static IValidatorBuilder NotEmpty(this IValidatorBuilder builder, 37 | Expression> selector, 38 | string key = null, 39 | string message = null) 40 | { 41 | if (builder is null) 42 | { 43 | throw new ArgumentNullException(nameof(builder)); 44 | } 45 | 46 | if (selector is null) 47 | { 48 | throw new ArgumentNullException(nameof(selector)); 49 | } 50 | 51 | key = key ?? selector.GetPropertyPath(); 52 | 53 | return builder.For(selector, p => p.NotEmpty(key, message)); 54 | } 55 | 56 | /// 57 | /// Adds a validator to ensure the value is an empty string. 58 | /// 59 | /// The validation builder. 60 | /// The key to use in broken rule. 61 | /// The message to use in broken rule. 62 | public static IValidatorBuilder Empty(this IValidatorBuilder builder, string key = null, string message = null) 63 | { 64 | if (builder is null) 65 | { 66 | throw new ArgumentNullException(nameof(builder)); 67 | } 68 | 69 | return builder 70 | .WhenNot( 71 | ctx => ctx.Value == string.Empty, 72 | ctx => ctx.AddBrokenRule(nameof(Empty), key, message ?? "Value must be empty.") 73 | ); 74 | } 75 | 76 | /// 77 | /// Adds a validator to ensure the value is an empty string for the target of the selector expression. 78 | /// 79 | /// The validation builder. 80 | /// The selector expression. 81 | /// The key to use in broken rule. 82 | /// The message to use in broken rule. 83 | public static IValidatorBuilder Empty(this IValidatorBuilder builder, 84 | Expression> selector, 85 | string key = null, 86 | string message = null) 87 | { 88 | if (builder is null) 89 | { 90 | throw new ArgumentNullException(nameof(builder)); 91 | } 92 | 93 | if (selector is null) 94 | { 95 | throw new ArgumentNullException(nameof(selector)); 96 | } 97 | 98 | key = key ?? selector.GetPropertyPath(); 99 | 100 | return builder.For(selector, p => p.Empty(key, message)); 101 | } 102 | 103 | /// 104 | /// Adds a validator to ensure the value matches a regular expression pattern. 105 | /// 106 | /// The validation builder. 107 | /// The regular expression pattern. 108 | /// The key to use in broken rule. 109 | /// The message to use in broken rule. 110 | public static IValidatorBuilder Regex(this IValidatorBuilder builder, 111 | string pattern, 112 | string key = null, 113 | string message = null) 114 | { 115 | if (builder is null) 116 | { 117 | throw new ArgumentNullException(nameof(builder)); 118 | } 119 | 120 | if (string.IsNullOrWhiteSpace(pattern)) 121 | { 122 | throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); 123 | } 124 | 125 | return builder 126 | .WhenNot( 127 | ctx => System.Text.RegularExpressions.Regex.IsMatch(ctx.Value ?? string.Empty, pattern), 128 | ctx => ctx.AddBrokenRule(nameof(Regex), key, message ?? "Value must match pattern.") 129 | ); 130 | } 131 | 132 | /// 133 | /// Adds a validator to ensure the value matches a regular expression pattern using specified regex options. 134 | /// 135 | /// The validation builder. 136 | /// The regular expression pattern. 137 | /// The regex options. 138 | /// The key to use in broken rule. 139 | /// The message to use in broken rule. 140 | public static IValidatorBuilder Regex(this IValidatorBuilder builder, 141 | string pattern, 142 | RegexOptions options, 143 | string key = null, 144 | string message = null) 145 | { 146 | if (builder is null) 147 | { 148 | throw new ArgumentNullException(nameof(builder)); 149 | } 150 | 151 | if (string.IsNullOrWhiteSpace(pattern)) 152 | { 153 | throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); 154 | } 155 | 156 | return builder 157 | .WhenNot( 158 | ctx => System.Text.RegularExpressions.Regex.IsMatch(ctx.Value ?? string.Empty, pattern, options), 159 | ctx => ctx.AddBrokenRule(nameof(Regex), key, message ?? "Value must match pattern.") 160 | ); 161 | } 162 | 163 | /// 164 | /// Adds a validator to ensure the value matches a regular expression pattern for the 165 | /// target of the selector expression. 166 | /// 167 | /// The validation builder. 168 | /// The selector expression. 169 | /// The regular expression pattern. 170 | /// The key to use in broken rule. 171 | /// The message to use in broken rule. 172 | public static IValidatorBuilder Regex(this IValidatorBuilder builder, 173 | Expression> selector, 174 | string pattern, 175 | string key = null, 176 | string message = null) 177 | { 178 | if (builder is null) 179 | { 180 | throw new ArgumentNullException(nameof(builder)); 181 | } 182 | 183 | if (selector is null) 184 | { 185 | throw new ArgumentNullException(nameof(selector)); 186 | } 187 | 188 | if (string.IsNullOrWhiteSpace(pattern)) 189 | { 190 | throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); 191 | } 192 | 193 | return builder.For(selector, p => p.Regex(pattern, key, message)); 194 | } 195 | 196 | /// 197 | /// Adds a validator to ensure the value matches a regular expression pattern for the 198 | /// target of the selector expression. 199 | /// 200 | /// The validation builder. 201 | /// The selector expression. 202 | /// The regular expression pattern. 203 | /// The regex options. 204 | /// The key to use in broken rule. 205 | /// The message to use in broken rule. 206 | public static IValidatorBuilder Regex(this IValidatorBuilder builder, 207 | Expression> selector, 208 | string pattern, 209 | RegexOptions options, 210 | string key = null, 211 | string message = null) 212 | { 213 | if (builder is null) 214 | { 215 | throw new ArgumentNullException(nameof(builder)); 216 | } 217 | 218 | if (selector is null) 219 | { 220 | throw new ArgumentNullException(nameof(selector)); 221 | } 222 | 223 | if (string.IsNullOrWhiteSpace(pattern)) 224 | { 225 | throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); 226 | } 227 | 228 | return builder.For(selector, p => p.Regex(pattern, options, key, message)); 229 | } 230 | 231 | /// 232 | /// Adds a validator to ensure the value starts with the specified value. 233 | /// 234 | /// The validation builder. 235 | /// The value the string starts with. 236 | /// The key to use in broken rule. 237 | /// The message to use in broken rule. 238 | public static IValidatorBuilder StartsWith(this IValidatorBuilder builder, string value, string key = null, string message = null) 239 | { 240 | if (builder is null) 241 | { 242 | throw new ArgumentNullException(nameof(builder)); 243 | } 244 | 245 | if (string.IsNullOrEmpty(value)) 246 | { 247 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 248 | } 249 | 250 | return builder 251 | .WhenNot( 252 | ctx => ctx.Value?.StartsWith(value) ?? false, 253 | ctx => ctx.AddBrokenRule(nameof(StartsWith), key, message ?? $"Value must start with '{value}'.") 254 | ); 255 | } 256 | 257 | /// 258 | /// Adds a validator to ensure the value starts with the specified for the target of the selector expression. 259 | /// 260 | /// The validation builder. 261 | /// The selector expression. 262 | /// The value the string starts with. 263 | /// The key to use in broken rule. 264 | /// The message to use in broken rule. 265 | public static IValidatorBuilder StartsWith(this IValidatorBuilder builder, 266 | Expression> selector, 267 | string value, 268 | string key = null, 269 | string message = null) 270 | { 271 | if (builder is null) 272 | { 273 | throw new ArgumentNullException(nameof(builder)); 274 | } 275 | 276 | if (selector is null) 277 | { 278 | throw new ArgumentNullException(nameof(selector)); 279 | } 280 | 281 | if (string.IsNullOrEmpty(value)) 282 | { 283 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 284 | } 285 | 286 | key = key ?? selector.GetPropertyPath(); 287 | 288 | return builder.For(selector, p => p.StartsWith(value, key, message)); 289 | } 290 | 291 | /// 292 | /// Adds a validator to ensure the value ends with the specified value. 293 | /// 294 | /// The validation builder. 295 | /// The value the string ends with. 296 | /// The key to use in broken rule. 297 | /// The message to use in broken rule. 298 | public static IValidatorBuilder EndsWith(this IValidatorBuilder builder, string value, string key = null, string message = null) 299 | { 300 | if (builder is null) 301 | { 302 | throw new ArgumentNullException(nameof(builder)); 303 | } 304 | 305 | if (string.IsNullOrEmpty(value)) 306 | { 307 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 308 | } 309 | 310 | return builder 311 | .WhenNot( 312 | ctx => ctx.Value?.EndsWith(value) ?? false, 313 | ctx => ctx.AddBrokenRule(nameof(EndsWith), key, message ?? $"Value must end with '{value}'.") 314 | ); 315 | } 316 | 317 | /// 318 | /// Adds a validator to ensure the value ends with the specified for the target of the selector expression. 319 | /// 320 | /// The validation builder. 321 | /// The selector expression. 322 | /// The value the string ends with. 323 | /// The key to use in broken rule. 324 | /// The message to use in broken rule. 325 | public static IValidatorBuilder EndsWith(this IValidatorBuilder builder, 326 | Expression> selector, 327 | string value, 328 | string key = null, 329 | string message = null) 330 | { 331 | if (builder is null) 332 | { 333 | throw new ArgumentNullException(nameof(builder)); 334 | } 335 | 336 | if (selector is null) 337 | { 338 | throw new ArgumentNullException(nameof(selector)); 339 | } 340 | 341 | if (string.IsNullOrEmpty(value)) 342 | { 343 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 344 | } 345 | 346 | key = key ?? selector.GetPropertyPath(); 347 | 348 | return builder.For(selector, p => p.EndsWith(value, key, message)); 349 | } 350 | 351 | /// 352 | /// Adds a validator to ensure the value contains the specified value. 353 | /// 354 | /// The validation builder. 355 | /// The value the string contains. 356 | /// The key to use in broken rule. 357 | /// The message to use in broken rule. 358 | public static IValidatorBuilder Contains(this IValidatorBuilder builder, string value, string key = null, string message = null) 359 | { 360 | if (builder is null) 361 | { 362 | throw new ArgumentNullException(nameof(builder)); 363 | } 364 | 365 | if (string.IsNullOrEmpty(value)) 366 | { 367 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 368 | } 369 | 370 | return builder 371 | .WhenNot( 372 | ctx => ctx.Value?.Contains(value) ?? false, 373 | ctx => ctx.AddBrokenRule(nameof(Contains), key, message ?? $"Value must contain '{value}'.") 374 | ); 375 | } 376 | 377 | /// 378 | /// Adds a validator to ensure the value contains the specified for the target of the selector expression. 379 | /// 380 | /// The validation builder. 381 | /// The selector expression. 382 | /// The value the string contains. 383 | /// The key to use in broken rule. 384 | /// The message to use in broken rule. 385 | public static IValidatorBuilder Contains(this IValidatorBuilder builder, 386 | Expression> selector, 387 | string value, 388 | string key = null, 389 | string message = null) 390 | { 391 | if (builder is null) 392 | { 393 | throw new ArgumentNullException(nameof(builder)); 394 | } 395 | 396 | if (selector is null) 397 | { 398 | throw new ArgumentNullException(nameof(selector)); 399 | } 400 | 401 | if (string.IsNullOrEmpty(value)) 402 | { 403 | throw new ArgumentException("Cannot be null or empty.", nameof(value)); 404 | } 405 | 406 | key = key ?? selector.GetPropertyPath(); 407 | 408 | return builder.For(selector, p => p.Contains(value, key, message)); 409 | } 410 | 411 | /// 412 | /// Adds a validator to ensure the value length is within a specified range. 413 | /// 414 | /// The validation builder. 415 | /// The minimum length. 416 | /// The maximum length. 417 | /// The key to use in broken rule. 418 | /// The message to use in broken rule. 419 | public static IValidatorBuilder Length(this IValidatorBuilder builder, int min, int max, string key = null, string message = null) 420 | { 421 | if (builder is null) 422 | { 423 | throw new ArgumentNullException(nameof(builder)); 424 | } 425 | 426 | if (min < 0) 427 | { 428 | throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); 429 | } 430 | 431 | if (min > max) 432 | { 433 | throw new ArgumentOutOfRangeException(nameof(min), min, $"Cannot be greater than max parameter (max '{max}')."); 434 | } 435 | 436 | return builder 437 | .When( 438 | ctx => ctx.Value is null || ctx.Value?.Length < min || ctx.Value?.Length > max, 439 | ctx => ctx.AddBrokenRule(nameof(Length), key, message ?? $"Value must be {min} to {max} characters in length.") 440 | ); 441 | } 442 | 443 | /// 444 | /// Adds a validator to ensure the value length is within a specified range. 445 | /// for the target of the selector expression. 446 | /// 447 | /// The validation builder. 448 | /// The selector expression. 449 | /// The minimum length. 450 | /// The maximum length. 451 | /// The key to use in broken rule. 452 | /// The message to use in broken rule. 453 | public static IValidatorBuilder Length(this IValidatorBuilder builder, 454 | Expression> selector, 455 | int min, 456 | int max, 457 | string key = null, 458 | string message = null) 459 | { 460 | if (builder is null) 461 | { 462 | throw new ArgumentNullException(nameof(builder)); 463 | } 464 | 465 | if (selector is null) 466 | { 467 | throw new ArgumentNullException(nameof(selector)); 468 | } 469 | 470 | if (min < 0) 471 | { 472 | throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); 473 | } 474 | 475 | if (min > max) 476 | { 477 | throw new ArgumentOutOfRangeException(nameof(min), min, $"Cannot be greater than max parameter (max '{max}')."); 478 | } 479 | 480 | key = key ?? selector.GetPropertyPath(); 481 | 482 | return builder.For(selector, p => p.Length(min, max, key, message)); 483 | } 484 | 485 | /// 486 | /// Adds a validator to ensure the value is of a minimum length. 487 | /// 488 | /// The validation builder. 489 | /// The minimum length. 490 | /// The key to use in broken rule. 491 | /// The message to use in broken rule. 492 | public static IValidatorBuilder MinLength(this IValidatorBuilder builder, int min, string key = null, string message = null) 493 | { 494 | if (builder is null) 495 | { 496 | throw new ArgumentNullException(nameof(builder)); 497 | } 498 | 499 | if (min < 0) 500 | { 501 | throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); 502 | } 503 | 504 | return builder 505 | .When( 506 | ctx => ctx.Value is null || ctx.Value?.Length < min, 507 | ctx => ctx.AddBrokenRule(nameof(MinLength), key, message ?? $"Value must have minimum length of {min}.") 508 | ); 509 | } 510 | 511 | /// 512 | /// Adds a validator to ensure the value is of a minimum length for the target of the selector expression. 513 | /// 514 | /// The validation builder. 515 | /// The selector expression. 516 | /// The minimum length. 517 | /// The key to use in broken rule. 518 | /// The message to use in broken rule. 519 | public static IValidatorBuilder MinLength(this IValidatorBuilder builder, 520 | Expression> selector, 521 | int min, 522 | string key = null, 523 | string message = null) 524 | { 525 | if (builder is null) 526 | { 527 | throw new ArgumentNullException(nameof(builder)); 528 | } 529 | 530 | if (selector is null) 531 | { 532 | throw new ArgumentNullException(nameof(selector)); 533 | } 534 | 535 | if (min < 0) 536 | { 537 | throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); 538 | } 539 | 540 | return builder.For(selector, p => p.MinLength(min, key, message)); 541 | } 542 | 543 | /// 544 | /// Adds a validator to ensure the value is not longer than maximum length. 545 | /// 546 | /// The validation builder. 547 | /// The maximum length. 548 | /// The key to use in broken rule. 549 | /// The message to use in broken rule. 550 | public static IValidatorBuilder MaxLength(this IValidatorBuilder builder, int max, string key = null, string message = null) 551 | { 552 | if (builder is null) 553 | { 554 | throw new ArgumentNullException(nameof(builder)); 555 | } 556 | 557 | if (max < 0) 558 | { 559 | throw new ArgumentOutOfRangeException(nameof(max), max, "Cannot be less than zero."); 560 | } 561 | 562 | return builder 563 | .When( 564 | ctx => ctx.Value?.Length > max, 565 | ctx => ctx.AddBrokenRule(nameof(MaxLength), key, message ?? $"Value must have maximum length of {max}.") 566 | ); 567 | } 568 | 569 | /// 570 | /// Adds a validator to ensure the value is of a maximum length for the target of the selector expression. 571 | /// 572 | /// The validation builder. 573 | /// The selector expression. 574 | /// The maximum length. 575 | /// The key to use in broken rule. 576 | /// The message to use in broken rule. 577 | public static IValidatorBuilder MaxLength(this IValidatorBuilder builder, 578 | Expression> selector, 579 | int max, 580 | string key = null, 581 | string message = null) 582 | { 583 | if (builder is null) 584 | { 585 | throw new ArgumentNullException(nameof(builder)); 586 | } 587 | 588 | if (selector is null) 589 | { 590 | throw new ArgumentNullException(nameof(selector)); 591 | } 592 | 593 | if (max < 0) 594 | { 595 | throw new ArgumentOutOfRangeException(nameof(max), max, "Cannot be less than zero."); 596 | } 597 | 598 | return builder.For(selector, p => p.MaxLength(max, key, message)); 599 | } 600 | 601 | /// 602 | /// Adds a validator to ensure the value is not null or empty or whitespace. 603 | /// 604 | /// The validation builder. 605 | /// The key to use in broken rule. 606 | /// The message to use in broken rule. 607 | public static IValidatorBuilder Required(this IValidatorBuilder builder, string key = null, string message = null) 608 | { 609 | if (builder is null) 610 | { 611 | throw new ArgumentNullException(nameof(builder)); 612 | } 613 | 614 | return builder 615 | .When( 616 | ctx => string.IsNullOrWhiteSpace(ctx.Value), 617 | ctx => ctx.AddBrokenRule(nameof(Required), key, message ?? $"Value is required.") 618 | ); 619 | } 620 | 621 | /// 622 | /// Adds a validator to ensure the value is not null or empty or whitespace for the target of the selector expression. 623 | /// 624 | /// The validation builder. 625 | /// The selector expression. 626 | /// The key to use in broken rule. 627 | /// The message to use in broken rule. 628 | public static IValidatorBuilder Required(this IValidatorBuilder builder, 629 | Expression> selector, 630 | string key = null, 631 | string message = null) 632 | { 633 | if (builder is null) 634 | { 635 | throw new ArgumentNullException(nameof(builder)); 636 | } 637 | 638 | if (selector is null) 639 | { 640 | throw new ArgumentNullException(nameof(selector)); 641 | } 642 | 643 | key = key ?? selector.GetPropertyPath(); 644 | 645 | return builder.For(selector, p => p.Required(key, message)); 646 | } 647 | 648 | private static readonly System.Text.RegularExpressions.Regex EmailRegex 649 | = new System.Text.RegularExpressions.Regex( 650 | @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", 651 | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); 652 | 653 | /// 654 | /// Adds a validator to ensure the value is an email address. 655 | /// 656 | /// The validation builder. 657 | /// The key to use in broken rule. 658 | /// The message to use in broken rule. 659 | public static IValidatorBuilder Email(this IValidatorBuilder builder, string key = null, string message = null) 660 | { 661 | if (builder is null) 662 | { 663 | throw new ArgumentNullException(nameof(builder)); 664 | } 665 | 666 | return builder 667 | .WhenNot( 668 | ctx => EmailRegex.IsMatch(ctx.Value ?? string.Empty), 669 | ctx => ctx.AddBrokenRule(nameof(Email), key, message ?? $"Value must be a valid email.") 670 | ); 671 | } 672 | 673 | /// 674 | /// Adds a validator to ensure the value is an email address for the target of the selector expression. 675 | /// 676 | /// The validation builder. 677 | /// The selector expression. 678 | /// The key to use in broken rule. 679 | /// The message to use in broken rule. 680 | public static IValidatorBuilder Email(this IValidatorBuilder builder, 681 | Expression> selector, 682 | string key = null, 683 | string message = null) 684 | { 685 | if (builder is null) 686 | { 687 | throw new ArgumentNullException(nameof(builder)); 688 | } 689 | 690 | if (selector is null) 691 | { 692 | throw new ArgumentNullException(nameof(selector)); 693 | } 694 | 695 | key = key ?? selector.GetPropertyPath(); 696 | 697 | return builder.For(selector, p => p.Email(key, message)); 698 | } 699 | } 700 | } -------------------------------------------------------------------------------- /src/Validatum/src/Extensions/ValidatorBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | 6 | namespace Validatum 7 | { 8 | /// 9 | /// Extension methods for adding validator delegates. 10 | /// 11 | public static partial class ValidatorBuilderExtensions 12 | { 13 | /// 14 | /// Adds a validator function targeting the type from the source object . 15 | /// 16 | /// The validator builder. 17 | /// The selector expression. 18 | /// The validator builder function. 19 | /// The source type. 20 | /// The target type. 21 | public static IValidatorBuilder For(this IValidatorBuilder builder, 22 | Expression> selector, 23 | Action> func) 24 | { 25 | if (builder is null) 26 | { 27 | throw new ArgumentNullException(nameof(builder)); 28 | } 29 | 30 | if (selector is null) 31 | { 32 | throw new ArgumentNullException(nameof(selector)); 33 | } 34 | 35 | if (func is null) 36 | { 37 | throw new ArgumentNullException(nameof(func)); 38 | } 39 | 40 | var label = selector.GetPropertyPath(); 41 | var selectorFunc = selector.Compile(); 42 | var propBuilder = new ValidatorBuilder

(); 43 | func(propBuilder); 44 | var propValidator = propBuilder.Build(label); 45 | 46 | return builder 47 | .With(ctx => 48 | { 49 | try 50 | { 51 | var value = selectorFunc(ctx.Value); 52 | var result = propValidator.Validate(value, ctx.Options); 53 | 54 | ctx.Merge(result); 55 | } 56 | catch (Exception ex) when (!(ex is ValidationException)) 57 | { 58 | if (ctx.Options.AddBrokenRuleForException) 59 | { 60 | ctx.AddBrokenRule(ex.GetType().Name, label, ex.Message); 61 | } 62 | else 63 | { 64 | throw new ValidationException(ex.Message, ex); 65 | } 66 | } 67 | }); 68 | } 69 | 70 | ///

71 | /// Adds a validator to validate all items in a collection from the target of the selector expression. 72 | /// 73 | /// The validator builder. 74 | /// The selector expression. 75 | /// The validator builder function. 76 | public static IValidatorBuilder ForEach(this IValidatorBuilder builder, 77 | Expression>> selector, 78 | Action> func) 79 | { 80 | if (builder is null) 81 | { 82 | throw new ArgumentNullException(nameof(builder)); 83 | } 84 | 85 | if (selector is null) 86 | { 87 | throw new ArgumentNullException(nameof(selector)); 88 | } 89 | 90 | if (func is null) 91 | { 92 | throw new ArgumentNullException(nameof(func)); 93 | } 94 | 95 | var label = selector.GetPropertyPath(); 96 | var selectorFunc = selector.Compile(); 97 | var itemValidatorBuilder = new ValidatorBuilder

(); 98 | func(itemValidatorBuilder); 99 | var itemValidator = itemValidatorBuilder.Build(label); 100 | 101 | return builder 102 | .With(ctx => 103 | { 104 | try 105 | { 106 | var items = selectorFunc(ctx.Value); 107 | 108 | foreach (var item in items.Select((x, i) => new { value = x, index = i })) 109 | { 110 | var result = itemValidator.Validate(item.value, ctx.Options); 111 | 112 | foreach (var brokenRule in result.BrokenRules) 113 | { 114 | ctx.AddBrokenRule(brokenRule.Rule, $"{brokenRule.Key}[{item.index}]", brokenRule.Message); 115 | } 116 | } 117 | } 118 | catch (Exception ex) when (!(ex is ValidationException)) 119 | { 120 | if (ctx.Options.AddBrokenRuleForException) 121 | { 122 | ctx.AddBrokenRule(ex.GetType().Name, label, ex.Message); 123 | } 124 | else 125 | { 126 | throw new ValidationException(ex.Message, ex); 127 | } 128 | } 129 | }); 130 | } 131 | 132 | ///

133 | /// Adds a validator function that will execute when the predicate resolves to true. 134 | /// 135 | /// The validator builder. 136 | /// The predicate. 137 | /// The function to execute. 138 | public static IValidatorBuilder When(this IValidatorBuilder builder, 139 | Func, bool> predicate, 140 | ValidatorDelegate func) 141 | { 142 | if (builder is null) 143 | { 144 | throw new ArgumentNullException(nameof(builder)); 145 | } 146 | 147 | if (predicate is null) 148 | { 149 | throw new ArgumentNullException(nameof(predicate)); 150 | } 151 | 152 | if (func is null) 153 | { 154 | throw new ArgumentNullException(nameof(func)); 155 | } 156 | 157 | return builder 158 | .With(ctx => 159 | { 160 | if (predicate(ctx)) 161 | { 162 | func(ctx); 163 | } 164 | }); 165 | } 166 | 167 | /// 168 | /// Adds a validator function that will execute when the predicate resolves to false. 169 | /// 170 | /// The validator builder. 171 | /// The predicate. 172 | /// The function to execute. 173 | public static IValidatorBuilder WhenNot(this IValidatorBuilder builder, 174 | Func, bool> predicate, 175 | ValidatorDelegate func) 176 | { 177 | if (builder is null) 178 | { 179 | throw new ArgumentNullException(nameof(builder)); 180 | } 181 | 182 | if (predicate is null) 183 | { 184 | throw new ArgumentNullException(nameof(predicate)); 185 | } 186 | 187 | if (func is null) 188 | { 189 | throw new ArgumentNullException(nameof(func)); 190 | } 191 | 192 | return builder 193 | .With(ctx => 194 | { 195 | if (!predicate(ctx)) 196 | { 197 | func(ctx); 198 | } 199 | }); 200 | } 201 | 202 | /// 203 | /// Executes validation if the predicate function is true. 204 | /// 205 | /// The valiator builder. 206 | /// The predicate function. 207 | /// The if builder function. 208 | public static IValidatorBuilder If(this IValidatorBuilder builder, 209 | Func, bool> predicate, 210 | Action> func) 211 | { 212 | if (builder is null) 213 | { 214 | throw new ArgumentNullException(nameof(builder)); 215 | } 216 | 217 | if (predicate is null) 218 | { 219 | throw new ArgumentNullException(nameof(predicate)); 220 | } 221 | 222 | if (func is null) 223 | { 224 | throw new ArgumentNullException(nameof(func)); 225 | } 226 | 227 | var ifBuilder = new ValidatorBuilder(); 228 | func(ifBuilder); 229 | var ifValidator = ifBuilder.Build(); 230 | 231 | return builder 232 | .When( 233 | ctx => predicate(ctx), 234 | ctx => 235 | { 236 | var result = ifValidator.Validate(ctx.Value, ctx.Options); 237 | 238 | ctx.Merge(result); 239 | }); 240 | } 241 | 242 | /// 243 | /// Continue executing validation if the current validation context is valid. 244 | /// 245 | /// The validator builder. 246 | /// The continue builder function. 247 | public static IValidatorBuilder Continue(this IValidatorBuilder builder, Action> func) 248 | => If(builder, ctx => ctx.IsValid, func); 249 | 250 | /// 251 | /// Adds an external validator to the validator. 252 | /// 253 | /// The validator builder. 254 | /// The external validator. 255 | public static IValidatorBuilder Validator(this IValidatorBuilder builder, Validator validator) 256 | { 257 | if (builder is null) 258 | { 259 | throw new ArgumentNullException(nameof(builder)); 260 | } 261 | 262 | if (validator is null) 263 | { 264 | throw new ArgumentNullException(nameof(validator)); 265 | } 266 | 267 | return builder 268 | .With(ctx => 269 | { 270 | var result = validator.Validate(ctx.Value, ctx.Options); 271 | 272 | ctx.Merge(result); 273 | }); 274 | } 275 | 276 | /// 277 | /// Adds an external validator to the target of the selector expression. 278 | /// 279 | /// The validator builder. 280 | /// The selector expression. 281 | /// The external validator. 282 | public static IValidatorBuilder Validator(this IValidatorBuilder builder, 283 | Expression> selector, 284 | Validator

validator) 285 | { 286 | if (builder is null) 287 | { 288 | throw new ArgumentNullException(nameof(builder)); 289 | } 290 | 291 | if (selector is null) 292 | { 293 | throw new ArgumentNullException(nameof(selector)); 294 | } 295 | 296 | if (validator is null) 297 | { 298 | throw new ArgumentNullException(nameof(validator)); 299 | } 300 | 301 | return builder.For(selector, p => p.Validator(validator)); 302 | } 303 | 304 | ///

305 | /// Aggregate broken rules into a single broken rule with the specified message. 306 | /// 307 | /// The validator builder. 308 | /// The message. 309 | public static IValidatorBuilder Message(this IValidatorBuilder builder, string message) 310 | { 311 | if (builder is null) 312 | { 313 | throw new ArgumentNullException(nameof(builder)); 314 | } 315 | 316 | if (string.IsNullOrWhiteSpace(message)) 317 | { 318 | throw new ArgumentException("message", nameof(message)); 319 | } 320 | 321 | return builder.WhenNot(ctx => ctx.IsValid, ctx => ctx.AggregateBrokenRules(message)); 322 | } 323 | 324 | /// 325 | /// Aggregate broken rules into a single broken rule using a function to build and return the message. 326 | /// 327 | /// The validator builder. 328 | /// The function to build and return a message. 329 | public static IValidatorBuilder Message(this IValidatorBuilder builder, Func, string> func) 330 | { 331 | if (builder is null) 332 | { 333 | throw new ArgumentNullException(nameof(builder)); 334 | } 335 | 336 | if (func is null) 337 | { 338 | throw new ArgumentNullException(nameof(func)); 339 | } 340 | 341 | return builder.WhenNot(ctx => ctx.IsValid, ctx => ctx.AggregateBrokenRules(func(ctx))); 342 | } 343 | } 344 | } -------------------------------------------------------------------------------- /src/Validatum/src/IValidatorBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Validatum 4 | { 5 | /// 6 | /// A builder for constructing validation delegate chains. 7 | /// 8 | /// The type being validated. 9 | public interface IValidatorBuilder 10 | { 11 | /// 12 | /// Builds the . 13 | /// 14 | /// A label to attach to the validator. 15 | Validator Build(string label = null); 16 | 17 | /// 18 | /// Adds a function to the validator. 19 | /// 20 | /// The function. 21 | IValidatorBuilder With(ValidatorDelegate func); 22 | } 23 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidationContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Validatum 6 | { 7 | /// 8 | /// Encapsulates validation specific data. 9 | /// 10 | /// The type being validated. 11 | public sealed class ValidationContext 12 | { 13 | private readonly List _brokenRules = new List(); 14 | 15 | /// 16 | /// Creates a new instance of ValidationContext 17 | /// 18 | /// The value to validate. 19 | /// The label. 20 | /// The validation options. 21 | public ValidationContext(T value, string label = null, ValidationOptions options = null) 22 | { 23 | Value = value; 24 | Label = label; 25 | Options = options ?? new ValidationOptions(); 26 | Options.Lock(); 27 | } 28 | 29 | /// 30 | /// Gets the value being validated. 31 | /// 32 | public T Value { get; } 33 | 34 | /// 35 | /// Gets the validation options. 36 | /// 37 | public ValidationOptions Options { get; } 38 | 39 | /// 40 | /// Gets the broken rules collection. 41 | /// 42 | public IEnumerable BrokenRules => _brokenRules; 43 | 44 | /// 45 | /// Gets a value indicating whether the context is in a valid state. 46 | /// 47 | public bool IsValid => _brokenRules.Count == 0; 48 | 49 | /// 50 | /// Gets the label. 51 | /// 52 | public string Label { get; } 53 | 54 | /// 55 | /// Indicates whether the validation context can continue processing. 56 | /// 57 | public bool CanContinue => IsValid || (!IsValid && !Options.StopWhenInvalid); 58 | 59 | /// 60 | /// Merges a validation result into this context. 61 | /// 62 | /// The validation result. 63 | public void Merge(ValidationResult result) 64 | { 65 | if (result is null) 66 | { 67 | throw new ArgumentNullException(nameof(result)); 68 | } 69 | 70 | foreach (var rule in result.BrokenRules) 71 | { 72 | AddBrokenRule(rule.Rule, rule.Key, rule.Message); 73 | } 74 | } 75 | 76 | /// 77 | /// Adds a broken rule to the context. 78 | /// 79 | /// The rule. 80 | /// The key. 81 | /// The message. 82 | public void AddBrokenRule(string rule, string key, string message) 83 | => _brokenRules.Add(new BrokenRule(rule, key ?? Label, message)); 84 | 85 | internal void AggregateBrokenRules(string message) 86 | { 87 | if (!IsValid) 88 | { 89 | var rules = string.Join(",", _brokenRules.Select(r => r.Rule)); 90 | 91 | _brokenRules.Clear(); 92 | 93 | AddBrokenRule(rules, Label, message); 94 | } 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Validatum 5 | { 6 | /// 7 | /// Represents errors that occur during validation execution. 8 | /// 9 | public class ValidationException : Exception 10 | { 11 | /// 12 | /// Creates a new instance of ValidationException containing broken rules. 13 | /// 14 | /// The broken rules. 15 | public ValidationException(IEnumerable brokenRules) 16 | { 17 | BrokenRules = brokenRules; 18 | } 19 | 20 | /// 21 | /// Creates a new instance of ValidationException with an error message and 22 | /// an inner exception that caused this exception. 23 | /// 24 | /// The error message. 25 | /// The inner exception. 26 | public ValidationException(string message, Exception innerException) 27 | : base(message, innerException) 28 | { 29 | 30 | } 31 | 32 | /// 33 | /// Gets the broken rules. 34 | /// 35 | public IEnumerable BrokenRules { get; } 36 | } 37 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidationOptions.cs: -------------------------------------------------------------------------------- 1 | namespace Validatum 2 | { 3 | /// 4 | /// Encapsulates options used for validation. 5 | /// 6 | public class ValidationOptions 7 | { 8 | private bool _locked = false; 9 | private SetOnce _stopWhenInvalid = new SetOnce(false); 10 | private SetOnce _addBrokenRuleForException = new SetOnce(true); 11 | private SetOnce _throwWhenInvalid = new SetOnce(false); 12 | 13 | /// 14 | /// Indicates to stop validation when the first invalid rule occurs. 15 | /// 16 | public bool StopWhenInvalid 17 | { 18 | get => _stopWhenInvalid.Value; 19 | set 20 | { 21 | if (!_locked) 22 | { 23 | _stopWhenInvalid.Value = value; 24 | } 25 | } 26 | } 27 | 28 | /// 29 | /// Indicates to add exceptions as broken rules when they occur. 30 | /// 31 | public bool AddBrokenRuleForException 32 | { 33 | get => _addBrokenRuleForException.Value; 34 | set 35 | { 36 | if (!_locked) 37 | { 38 | _addBrokenRuleForException.Value = value; 39 | } 40 | } 41 | } 42 | 43 | /// 44 | /// Indicates to throw when validation fails. 45 | /// 46 | public bool ThrowWhenInvalid 47 | { 48 | get => _throwWhenInvalid.Value; 49 | set 50 | { 51 | if (!_locked) 52 | { 53 | _throwWhenInvalid.Value = value; 54 | } 55 | } 56 | } 57 | 58 | internal void Lock() 59 | { 60 | _locked = true; 61 | } 62 | 63 | private struct SetOnce 64 | { 65 | public SetOnce(T defaultValue) 66 | { 67 | _value = defaultValue; 68 | _isSet = false; 69 | } 70 | 71 | private bool _isSet; 72 | private T _value; 73 | 74 | public T Value 75 | { 76 | get => _value; 77 | set 78 | { 79 | if (!_isSet) 80 | { 81 | _value = value; 82 | _isSet = true; 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidationResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | 5 | namespace Validatum 6 | { 7 | /// 8 | /// Encapsulates data collected during validation. 9 | /// 10 | public class ValidationResult 11 | { 12 | /// 13 | /// Creates a new instance of ValidationResult. 14 | /// 15 | /// The broken rules. 16 | public ValidationResult(IEnumerable brokenRules) 17 | { 18 | BrokenRules = new ReadOnlyCollection((brokenRules ?? Enumerable.Empty()).ToList()); 19 | } 20 | 21 | /// 22 | /// Gets the collection of broken rules. 23 | /// 24 | public IReadOnlyCollection BrokenRules { get; } 25 | 26 | /// 27 | /// Gets a value indicating if the result is valid. 28 | /// 29 | public bool IsValid => BrokenRules.Count() == 0; 30 | } 31 | } -------------------------------------------------------------------------------- /src/Validatum/src/Validator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Validatum 4 | { 5 | /// 6 | /// A class that can validate values of a specified type. 7 | /// 8 | /// The type of data being validated. 9 | public sealed class Validator 10 | { 11 | private readonly ValidatorDelegate _function; 12 | 13 | /// 14 | /// Creates a new instance of Validator. 15 | /// 16 | /// The root validator function. 17 | /// The label to attach to the validator (optional). 18 | internal Validator(ValidatorDelegate function, string label = null) 19 | { 20 | _function = function ?? throw new ArgumentNullException(nameof(function)); 21 | Label = label; 22 | } 23 | 24 | /// 25 | /// Gets the label. 26 | /// 27 | public string Label { get; } 28 | 29 | /// 30 | /// Validates a value against the validator function. 31 | /// 32 | /// The value to validate. 33 | /// The validation options. 34 | public ValidationResult Validate(T value, ValidationOptions options = null) 35 | { 36 | var context = new ValidationContext(value, Label, options); 37 | 38 | _function(context); 39 | 40 | return new ValidationResult(context.BrokenRules); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidatorBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Validatum 5 | { 6 | /// 7 | /// Default implementation for . 8 | /// 9 | /// The type being validated. 10 | public sealed class ValidatorBuilder : IValidatorBuilder 11 | { 12 | private readonly Stack, ValidatorDelegate>> _delegates 13 | = new Stack, ValidatorDelegate>>(); 14 | 15 | private static readonly Func, ValidatorDelegate> Run = next => ctx => 16 | { 17 | next(ctx); 18 | 19 | if (!ctx.IsValid && ctx.Options.ThrowWhenInvalid) 20 | { 21 | throw new ValidationException(ctx.BrokenRules); 22 | } 23 | }; 24 | 25 | private Validator _validator; 26 | 27 | private void AddDelegate(Action, ValidatorDelegate> func) 28 | { 29 | if (func is null) 30 | { 31 | throw new ArgumentNullException(nameof(func)); 32 | } 33 | 34 | _delegates.Push(next => ctx => 35 | { 36 | if (ctx.CanContinue) 37 | { 38 | func(ctx, next); 39 | } 40 | }); 41 | } 42 | 43 | /// 44 | public Validator Build(string label = null) 45 | { 46 | if (_validator is null) 47 | { 48 | ValidatorDelegate validator = ctx => { }; 49 | 50 | while (_delegates.Count > 0) 51 | { 52 | var next = _delegates.Pop(); 53 | validator = next(validator); 54 | } 55 | 56 | validator = Run(validator); 57 | 58 | _validator = new Validator(validator, label ?? typeof(T).Name); 59 | } 60 | 61 | return _validator; 62 | } 63 | 64 | /// 65 | public IValidatorBuilder With(ValidatorDelegate func) 66 | { 67 | if (func is null) 68 | { 69 | throw new ArgumentNullException(nameof(func)); 70 | } 71 | 72 | AddDelegate((ctx, next) => 73 | { 74 | try 75 | { 76 | func(ctx); 77 | } 78 | catch (Exception ex) when (!(ex is ValidationException)) 79 | { 80 | if (ctx.Options.AddBrokenRuleForException) 81 | { 82 | ctx.AddBrokenRule(ex.GetType().Name, ctx.Label, ex.Message); 83 | } 84 | else 85 | { 86 | throw new ValidationException(ex.Message, ex); 87 | } 88 | } 89 | 90 | if (ctx.CanContinue) 91 | { 92 | next(ctx); 93 | } 94 | }); 95 | 96 | return this; 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /src/Validatum/src/ValidatorDelegate.cs: -------------------------------------------------------------------------------- 1 | namespace Validatum 2 | { 3 | /// 4 | /// A function that processes validation logic. 5 | /// 6 | /// The validation context. 7 | /// The type being validated. 8 | public delegate void ValidatorDelegate(ValidationContext context); 9 | } -------------------------------------------------------------------------------- /src/Validatum/src/Validatum.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | bin\Validatum.xml 7 | 8 8 | 9 | 10 | 11 | true 12 | Validatum 13 | 1.1.0 14 | Brad Sheldrick 15 | MIT 16 | Validation;Fluent;Builder 17 | A library for building fluent validation functions for .NET. 18 | Brad Sheldrick 19 | https://bsheldrick.github.io/validatum 20 | https://github.com/bsheldrick/validatum 21 | git 22 | 23 | 24 | 25 | 26 | <_Parameter1>Validatum.Tests 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/Validatum/test/TestClasses.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Validatum.Tests 5 | { 6 | public class Employee 7 | { 8 | public int Id { get; set; } 9 | public Company Employer { get; set; } 10 | public Employee Manager { get; set; } 11 | public string Role { get; set; } 12 | public string FirstName { get; set; } 13 | public string LastName { get; set; } 14 | public string Email { get; set; } 15 | public string Phone { get; set; } 16 | public string[] Skills { get; set; } 17 | public decimal Salary { get; set; } 18 | public decimal SalaryCommenced { get; set; } 19 | public DateTime Commenced { get; set; } 20 | public bool Active { get; set; } 21 | } 22 | 23 | public class Company 24 | { 25 | public int Id { get; set; } 26 | public string Name { get; set; } 27 | public IEnumerable Employees { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Validatum/test/ValidatorBuilderExtensions.Boolean.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Xunit; 4 | 5 | namespace Validatum.Tests 6 | { 7 | public class ValidatorBuilderBooleanExtensionsTests 8 | { 9 | [Fact] 10 | public void True_ThrowsException_WhenBuilderIsNull() 11 | { 12 | Assert.Throws("builder", () => 13 | { 14 | ValidatorBuilderExtensions.True(null); 15 | }); 16 | } 17 | 18 | [Fact] 19 | public void True_ShouldAddBrokenRule_WhenValueIsFalse() 20 | { 21 | // arrange 22 | var validator = new ValidatorBuilder() 23 | .True() 24 | .Build(); 25 | 26 | // act 27 | var result = validator.Validate(false); 28 | var brokenRule = result.BrokenRules.FirstOrDefault(); 29 | 30 | // assert 31 | Assert.NotNull(brokenRule); 32 | Assert.Equal("True", brokenRule.Rule); 33 | Assert.Equal("Boolean", brokenRule.Key); 34 | Assert.Equal("Value must be true.", brokenRule.Message); 35 | } 36 | 37 | [Fact] 38 | public void True_ShouldNotAddBrokenRule_WhenValueIsTrue() 39 | { 40 | // arrange 41 | var validator = new ValidatorBuilder() 42 | .True() 43 | .Build(); 44 | 45 | // act 46 | var result = validator.Validate(true); 47 | 48 | // assert 49 | Assert.Empty(result.BrokenRules); 50 | } 51 | 52 | [Fact] 53 | public void True_ShouldPassKeyToBrokenRule_WhenKeyProvided() 54 | { 55 | // arrange 56 | var validator = new ValidatorBuilder() 57 | .True("test") 58 | .Build(); 59 | 60 | // act 61 | var result = validator.Validate(false); 62 | var brokenRule = result.BrokenRules.FirstOrDefault(); 63 | 64 | // assert 65 | Assert.Equal("test", brokenRule.Key); 66 | } 67 | 68 | [Fact] 69 | public void True_ShouldPassMessageToBrokenRule_WhenMessageProvided() 70 | { 71 | // arrange 72 | var validator = new ValidatorBuilder() 73 | .True(message: "test") 74 | .Build(); 75 | 76 | // act 77 | var result = validator.Validate(false); 78 | var brokenRule = result.BrokenRules.FirstOrDefault(); 79 | 80 | // assert 81 | Assert.Equal("test", brokenRule.Message); 82 | } 83 | 84 | [Fact] 85 | public void TrueFor_ThrowsException_WhenBuilderIsNull() 86 | { 87 | Assert.Throws("builder", () => 88 | { 89 | ValidatorBuilderExtensions.True(null, null); 90 | }); 91 | } 92 | 93 | [Fact] 94 | public void TrueFor_ThrowsException_WhenSelectorIsNull() 95 | { 96 | Assert.Throws("selector", () => 97 | { 98 | ValidatorBuilderExtensions.True(new ValidatorBuilder(), null); 99 | }); 100 | } 101 | 102 | [Fact] 103 | public void TrueFor_ShouldAddBrokenRule_WhenValueIsFalse() 104 | { 105 | // arrange 106 | var validator = new ValidatorBuilder() 107 | .True(e => e.Active) 108 | .Build(); 109 | 110 | // act 111 | var result = validator.Validate(new Employee { Active = false }); 112 | var brokenRule = result.BrokenRules.FirstOrDefault(); 113 | 114 | // assert 115 | Assert.NotNull(brokenRule); 116 | Assert.Equal("True", brokenRule.Rule); 117 | Assert.Equal("Active", brokenRule.Key); 118 | Assert.Equal("Value must be true.", brokenRule.Message); 119 | } 120 | 121 | [Fact] 122 | public void TrueFor_ShouldNotAddBrokenRule_WhenValueIsTrue() 123 | { 124 | // arrange 125 | var validator = new ValidatorBuilder() 126 | .True(e => e.Active) 127 | .Build(); 128 | 129 | // act 130 | var result = validator.Validate(new Employee { Active = true }); 131 | 132 | // assert 133 | Assert.Empty(result.BrokenRules); 134 | } 135 | 136 | [Fact] 137 | public void TrueFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 138 | { 139 | // arrange 140 | var validator = new ValidatorBuilder() 141 | .True(e => e.Active, "test") 142 | .Build(); 143 | 144 | // act 145 | var result = validator.Validate(new Employee()); 146 | var brokenRule = result.BrokenRules.FirstOrDefault(); 147 | 148 | // assert 149 | Assert.Equal("test", brokenRule.Key); 150 | } 151 | 152 | [Fact] 153 | public void TrueFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 154 | { 155 | // arrange 156 | var validator = new ValidatorBuilder() 157 | .True(e => e.Active, message: "test") 158 | .Build(); 159 | 160 | // act 161 | var result = validator.Validate(new Employee()); 162 | var brokenRule = result.BrokenRules.FirstOrDefault(); 163 | 164 | // assert 165 | Assert.Equal("test", brokenRule.Message); 166 | } 167 | 168 | [Fact] 169 | public void False_ThrowsException_WhenBuilderIsNull() 170 | { 171 | Assert.Throws("builder", () => 172 | { 173 | ValidatorBuilderExtensions.False(null); 174 | }); 175 | } 176 | 177 | [Fact] 178 | public void False_ShouldAddBrokenRule_WhenValueIsTrue() 179 | { 180 | // arrange 181 | var validator = new ValidatorBuilder() 182 | .False() 183 | .Build(); 184 | 185 | // act 186 | var result = validator.Validate(true); 187 | var brokenRule = result.BrokenRules.FirstOrDefault(); 188 | 189 | // assert 190 | Assert.NotNull(brokenRule); 191 | Assert.Equal("False", brokenRule.Rule); 192 | Assert.Equal("Boolean", brokenRule.Key); 193 | Assert.Equal("Value must be false.", brokenRule.Message); 194 | } 195 | 196 | [Fact] 197 | public void False_ShouldNotAddBrokenRule_WhenValueIsFalse() 198 | { 199 | // arrange 200 | var validator = new ValidatorBuilder() 201 | .False() 202 | .Build(); 203 | 204 | // act 205 | var result = validator.Validate(false); 206 | 207 | // assert 208 | Assert.Empty(result.BrokenRules); 209 | } 210 | 211 | [Fact] 212 | public void False_ShouldPassKeyToBrokenRule_WhenKeyProvided() 213 | { 214 | // arrange 215 | var validator = new ValidatorBuilder() 216 | .False("test") 217 | .Build(); 218 | 219 | // act 220 | var result = validator.Validate(true); 221 | var brokenRule = result.BrokenRules.FirstOrDefault(); 222 | 223 | // assert 224 | Assert.Equal("test", brokenRule.Key); 225 | } 226 | 227 | [Fact] 228 | public void False_ShouldPassMessageToBrokenRule_WhenMessageProvided() 229 | { 230 | // arrange 231 | var validator = new ValidatorBuilder() 232 | .False(message: "test") 233 | .Build(); 234 | 235 | // act 236 | var result = validator.Validate(true); 237 | var brokenRule = result.BrokenRules.FirstOrDefault(); 238 | 239 | // assert 240 | Assert.Equal("test", brokenRule.Message); 241 | } 242 | 243 | [Fact] 244 | public void FalseFor_ThrowsException_WhenBuilderIsNull() 245 | { 246 | Assert.Throws("builder", () => 247 | { 248 | ValidatorBuilderExtensions.False(null, null); 249 | }); 250 | } 251 | 252 | [Fact] 253 | public void FalseFor_ThrowsException_WhenSelectorIsNull() 254 | { 255 | Assert.Throws("selector", () => 256 | { 257 | ValidatorBuilderExtensions.False(new ValidatorBuilder(), null); 258 | }); 259 | } 260 | 261 | [Fact] 262 | public void FalseFor_ShouldAddBrokenRule_WhenValueIsTrue() 263 | { 264 | // arrange 265 | var validator = new ValidatorBuilder() 266 | .False(e => e.Active) 267 | .Build(); 268 | 269 | // act 270 | var result = validator.Validate(new Employee { Active = true }); 271 | var brokenRule = result.BrokenRules.FirstOrDefault(); 272 | 273 | // assert 274 | Assert.NotNull(brokenRule); 275 | Assert.Equal("False", brokenRule.Rule); 276 | Assert.Equal("Active", brokenRule.Key); 277 | Assert.Equal("Value must be false.", brokenRule.Message); 278 | } 279 | 280 | [Fact] 281 | public void FalseFor_ShouldNotAddBrokenRule_WhenValueIsFalse() 282 | { 283 | // arrange 284 | var validator = new ValidatorBuilder() 285 | .False(e => e.Active) 286 | .Build(); 287 | 288 | // act 289 | var result = validator.Validate(new Employee { Active = false }); 290 | 291 | // assert 292 | Assert.Empty(result.BrokenRules); 293 | } 294 | 295 | [Fact] 296 | public void FalseFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 297 | { 298 | // arrange 299 | var validator = new ValidatorBuilder() 300 | .False(e => e.Active, "test") 301 | .Build(); 302 | 303 | // act 304 | var result = validator.Validate(new Employee { Active = true }); 305 | var brokenRule = result.BrokenRules.FirstOrDefault(); 306 | 307 | // assert 308 | Assert.Equal("test", brokenRule.Key); 309 | } 310 | 311 | [Fact] 312 | public void FalseFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 313 | { 314 | // arrange 315 | var validator = new ValidatorBuilder() 316 | .False(e => e.Active, message: "test") 317 | .Build(); 318 | 319 | // act 320 | var result = validator.Validate(new Employee { Active = true }); 321 | var brokenRule = result.BrokenRules.FirstOrDefault(); 322 | 323 | // assert 324 | Assert.Equal("test", brokenRule.Message); 325 | } 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /src/Validatum/test/ValidatorBuilderExtensions.Collections.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Xunit; 5 | 6 | namespace Validatum.Tests 7 | { 8 | public class ValidatorBuilderCollectionExtensionsTests 9 | { 10 | [Fact] 11 | public void Count_ThrowsException_WhenBuilderIsNull() 12 | { 13 | Assert.Throws("builder", () => 14 | { 15 | ValidatorBuilderExtensions.Count(null, 0); 16 | }); 17 | } 18 | 19 | [Fact] 20 | public void Count_ThrowsException_WhenCountLessThanZero() 21 | { 22 | Assert.Throws("count", () => 23 | { 24 | ValidatorBuilderExtensions.Count(new ValidatorBuilder>(), -1); 25 | }); 26 | } 27 | 28 | [Fact] 29 | public void Count_ShouldAddBrokenRule_WhenCollectionCount_LessThanCount() 30 | { 31 | // arrange 32 | var validator = new ValidatorBuilder>() 33 | .Count(1) 34 | .Build(); 35 | 36 | // act 37 | var result = validator.Validate(new List()); 38 | var brokenRule = result.BrokenRules.FirstOrDefault(); 39 | 40 | // assert 41 | Assert.NotNull(brokenRule); 42 | Assert.Equal("Count", brokenRule.Rule); 43 | Assert.Equal("IEnumerable", brokenRule.Key); 44 | Assert.Equal("Collection count must equal 1.", brokenRule.Message); 45 | } 46 | 47 | [Fact] 48 | public void Count_ShouldAddBrokenRule_WhenCollectionCount_GreaterThanCount() 49 | { 50 | // arrange 51 | var validator = new ValidatorBuilder>() 52 | .Count(1) 53 | .Build(); 54 | 55 | // act 56 | var result = validator.Validate(new List(new[] { "test", "hello" })); 57 | var brokenRule = result.BrokenRules.FirstOrDefault(); 58 | 59 | // assert 60 | Assert.NotNull(brokenRule); 61 | Assert.Equal("Count", brokenRule.Rule); 62 | Assert.Equal("IEnumerable", brokenRule.Key); 63 | Assert.Equal("Collection count must equal 1.", brokenRule.Message); 64 | } 65 | 66 | [Fact] 67 | public void Count_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToCount() 68 | { 69 | // arrange 70 | var validator = new ValidatorBuilder>() 71 | .Count(1) 72 | .Build(); 73 | 74 | // act 75 | var result = validator.Validate(new[] { "hello" }); 76 | 77 | // assert 78 | Assert.Empty(result.BrokenRules); 79 | } 80 | 81 | [Fact] 82 | public void Count_ShouldPassKeyToBrokenRule_WhenKeyProvided() 83 | { 84 | // arrange 85 | var validator = new ValidatorBuilder>() 86 | .Count(1, "test") 87 | .Build(); 88 | 89 | // act 90 | var result = validator.Validate(new List()); 91 | var brokenRule = result.BrokenRules.FirstOrDefault(); 92 | 93 | // assert 94 | Assert.Equal("test", brokenRule.Key); 95 | } 96 | 97 | [Fact] 98 | public void Count_ShouldPassMessageToBrokenRule_WhenMessageProvided() 99 | { 100 | // arrange 101 | var validator = new ValidatorBuilder>() 102 | .Count(1, message: "test") 103 | .Build(); 104 | 105 | // act 106 | var result = validator.Validate(new List()); 107 | var brokenRule = result.BrokenRules.FirstOrDefault(); 108 | 109 | // assert 110 | Assert.Equal("test", brokenRule.Message); 111 | } 112 | 113 | [Fact] 114 | public void CountFor_ThrowsException_WhenBuilderIsNull() 115 | { 116 | Assert.Throws("builder", () => 117 | { 118 | ValidatorBuilderExtensions.Count(null, null, 0); 119 | }); 120 | } 121 | 122 | [Fact] 123 | public void CountFor_ThrowsException_WhenSelectorIsNull() 124 | { 125 | Assert.Throws("selector", () => 126 | { 127 | ValidatorBuilderExtensions.Count(new ValidatorBuilder(), null, 0); 128 | }); 129 | } 130 | 131 | [Fact] 132 | public void CountFor_ThrowsException_WhenCountLessThanZero() 133 | { 134 | Assert.Throws("count", () => 135 | { 136 | ValidatorBuilderExtensions.Count(new ValidatorBuilder(), e => e.Skills, -1); 137 | }); 138 | } 139 | 140 | [Fact] 141 | public void CountFor_ShouldAddBrokenRule_WhenCollectionCount_LessThanCount() 142 | { 143 | // arrange 144 | var validator = new ValidatorBuilder() 145 | .Count(e => e.Skills, 1) 146 | .Build(); 147 | 148 | // act 149 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 150 | var brokenRule = result.BrokenRules.FirstOrDefault(); 151 | 152 | // assert 153 | Assert.NotNull(brokenRule); 154 | Assert.Equal("Count", brokenRule.Rule); 155 | Assert.Equal("Skills", brokenRule.Key); 156 | Assert.Equal("Collection count must equal 1.", brokenRule.Message); 157 | } 158 | 159 | [Fact] 160 | public void CountFor_ShouldAddBrokenRule_WhenCollectionCount_GreaterThanCount() 161 | { 162 | // arrange 163 | var validator = new ValidatorBuilder() 164 | .Count(e => e.Skills, 1) 165 | .Build(); 166 | 167 | // act 168 | var result = validator.Validate(new Employee { Skills = new[] { "test", "hello" } }); 169 | var brokenRule = result.BrokenRules.FirstOrDefault(); 170 | 171 | // assert 172 | Assert.NotNull(brokenRule); 173 | Assert.Equal("Count", brokenRule.Rule); 174 | Assert.Equal("Skills", brokenRule.Key); 175 | Assert.Equal("Collection count must equal 1.", brokenRule.Message); 176 | } 177 | 178 | [Fact] 179 | public void CountFor_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToCount() 180 | { 181 | // arrange 182 | var validator = new ValidatorBuilder() 183 | .Count(e => e.Skills, 1) 184 | .Build(); 185 | 186 | // act 187 | var result = validator.Validate(new Employee { Skills = new[] { "hello" } }); 188 | 189 | // assert 190 | Assert.Empty(result.BrokenRules); 191 | } 192 | 193 | [Fact] 194 | public void CountFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 195 | { 196 | // arrange 197 | var validator = new ValidatorBuilder() 198 | .Count(e => e.Skills, 1, "test") 199 | .Build(); 200 | 201 | // act 202 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 203 | var brokenRule = result.BrokenRules.FirstOrDefault(); 204 | 205 | // assert 206 | Assert.Equal("test", brokenRule.Key); 207 | } 208 | 209 | [Fact] 210 | public void CountFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 211 | { 212 | // arrange 213 | var validator = new ValidatorBuilder() 214 | .Count(e => e.Skills, 1, message: "test") 215 | .Build(); 216 | 217 | // act 218 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 219 | var brokenRule = result.BrokenRules.FirstOrDefault(); 220 | 221 | // assert 222 | Assert.Equal("test", brokenRule.Message); 223 | } 224 | 225 | [Fact] 226 | public void MinCount_ThrowsException_WhenBuilderIsNull() 227 | { 228 | Assert.Throws("builder", () => 229 | { 230 | ValidatorBuilderExtensions.MinCount(null, 0); 231 | }); 232 | } 233 | 234 | [Fact] 235 | public void MinCount_ThrowsException_WhenCountLessThanZero() 236 | { 237 | Assert.Throws("count", () => 238 | { 239 | ValidatorBuilderExtensions.MinCount(new ValidatorBuilder>(), -1); 240 | }); 241 | } 242 | 243 | [Fact] 244 | public void MinCount_ShouldAddBrokenRule_WhenCollectionCount_LessThanCount() 245 | { 246 | // arrange 247 | var validator = new ValidatorBuilder>() 248 | .MinCount(1) 249 | .Build(); 250 | 251 | // act 252 | var result = validator.Validate(new List()); 253 | var brokenRule = result.BrokenRules.FirstOrDefault(); 254 | 255 | // assert 256 | Assert.NotNull(brokenRule); 257 | Assert.Equal("MinCount", brokenRule.Rule); 258 | Assert.Equal("IEnumerable", brokenRule.Key); 259 | Assert.Equal("Collection count must be at least 1.", brokenRule.Message); 260 | } 261 | 262 | [Fact] 263 | public void MinCount_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToMinCount() 264 | { 265 | // arrange 266 | var validator = new ValidatorBuilder>() 267 | .MinCount(1) 268 | .Build(); 269 | 270 | // act 271 | var result = validator.Validate(new[] { "hello" }); 272 | 273 | // assert 274 | Assert.Empty(result.BrokenRules); 275 | } 276 | 277 | [Fact] 278 | public void MinCount_ShouldNotAddBrokenRule_WhenCollectionCount_GreaterThanMinCount() 279 | { 280 | // arrange 281 | var validator = new ValidatorBuilder>() 282 | .MinCount(1) 283 | .Build(); 284 | 285 | // act 286 | var result = validator.Validate(new[] { "hello", "test" }); 287 | 288 | // assert 289 | Assert.Empty(result.BrokenRules); 290 | } 291 | 292 | [Fact] 293 | public void MinCount_ShouldPassKeyToBrokenRule_WhenKeyProvided() 294 | { 295 | // arrange 296 | var validator = new ValidatorBuilder>() 297 | .MinCount(1, "test") 298 | .Build(); 299 | 300 | // act 301 | var result = validator.Validate(new List()); 302 | var brokenRule = result.BrokenRules.FirstOrDefault(); 303 | 304 | // assert 305 | Assert.Equal("test", brokenRule.Key); 306 | } 307 | 308 | [Fact] 309 | public void MinCount_ShouldPassMessageToBrokenRule_WhenMessageProvided() 310 | { 311 | // arrange 312 | var validator = new ValidatorBuilder>() 313 | .MinCount(1, message: "test") 314 | .Build(); 315 | 316 | // act 317 | var result = validator.Validate(new List()); 318 | var brokenRule = result.BrokenRules.FirstOrDefault(); 319 | 320 | // assert 321 | Assert.Equal("test", brokenRule.Message); 322 | } 323 | 324 | [Fact] 325 | public void MinCountFor_ThrowsException_WhenBuilderIsNull() 326 | { 327 | Assert.Throws("builder", () => 328 | { 329 | ValidatorBuilderExtensions.MinCount(null, null, 0); 330 | }); 331 | } 332 | 333 | [Fact] 334 | public void MinCountFor_ThrowsException_WhenSelectorIsNull() 335 | { 336 | Assert.Throws("selector", () => 337 | { 338 | ValidatorBuilderExtensions.MinCount(new ValidatorBuilder(), null, 0); 339 | }); 340 | } 341 | 342 | [Fact] 343 | public void MinCountFor_ThrowsException_WhenCountLessThanZero() 344 | { 345 | Assert.Throws("count", () => 346 | { 347 | ValidatorBuilderExtensions.MinCount(new ValidatorBuilder(), e => e.Skills, -1); 348 | }); 349 | } 350 | 351 | [Fact] 352 | public void MinCountFor_ShouldAddBrokenRule_WhenCollectionCount_LessThanMinCount() 353 | { 354 | // arrange 355 | var validator = new ValidatorBuilder() 356 | .MinCount(e => e.Skills, 1) 357 | .Build(); 358 | 359 | // act 360 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 361 | var brokenRule = result.BrokenRules.FirstOrDefault(); 362 | 363 | // assert 364 | Assert.NotNull(brokenRule); 365 | Assert.Equal("MinCount", brokenRule.Rule); 366 | Assert.Equal("Skills", brokenRule.Key); 367 | Assert.Equal("Collection count must be at least 1.", brokenRule.Message); 368 | } 369 | 370 | [Fact] 371 | public void MinCountFor_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToMinCount() 372 | { 373 | // arrange 374 | var validator = new ValidatorBuilder() 375 | .MinCount(e => e.Skills, 1) 376 | .Build(); 377 | 378 | // act 379 | var result = validator.Validate(new Employee { Skills = new[] { "hello" } }); 380 | 381 | // assert 382 | Assert.Empty(result.BrokenRules); 383 | } 384 | 385 | [Fact] 386 | public void MinCountFor_ShouldNotAddBrokenRule_WhenCollectionCount_GreaterThanMinCount() 387 | { 388 | // arrange 389 | var validator = new ValidatorBuilder() 390 | .MinCount(e => e.Skills, 1) 391 | .Build(); 392 | 393 | // act 394 | var result = validator.Validate(new Employee { Skills = new[] { "hello", "test" } }); 395 | 396 | // assert 397 | Assert.Empty(result.BrokenRules); 398 | } 399 | 400 | [Fact] 401 | public void MinCountFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 402 | { 403 | // arrange 404 | var validator = new ValidatorBuilder() 405 | .MinCount(e => e.Skills, 1, "test") 406 | .Build(); 407 | 408 | // act 409 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 410 | var brokenRule = result.BrokenRules.FirstOrDefault(); 411 | 412 | // assert 413 | Assert.Equal("test", brokenRule.Key); 414 | } 415 | 416 | [Fact] 417 | public void MinCountFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 418 | { 419 | // arrange 420 | var validator = new ValidatorBuilder() 421 | .MinCount(e => e.Skills, 1, message: "test") 422 | .Build(); 423 | 424 | // act 425 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 426 | var brokenRule = result.BrokenRules.FirstOrDefault(); 427 | 428 | // assert 429 | Assert.Equal("test", brokenRule.Message); 430 | } 431 | 432 | [Fact] 433 | public void MaxCount_ThrowsException_WhenBuilderIsNull() 434 | { 435 | Assert.Throws("builder", () => 436 | { 437 | ValidatorBuilderExtensions.MaxCount(null, 0); 438 | }); 439 | } 440 | 441 | [Fact] 442 | public void MaxCount_ThrowsException_WhenCountLessThanZero() 443 | { 444 | Assert.Throws("count", () => 445 | { 446 | ValidatorBuilderExtensions.MaxCount(new ValidatorBuilder>(), -1); 447 | }); 448 | } 449 | 450 | [Fact] 451 | public void MaxCount_ShouldAddBrokenRule_WhenCollectionCount_GreaterThanCount() 452 | { 453 | // arrange 454 | var validator = new ValidatorBuilder>() 455 | .MaxCount(1) 456 | .Build(); 457 | 458 | // act 459 | var result = validator.Validate(new List(new[] { "test", "hello" })); 460 | var brokenRule = result.BrokenRules.FirstOrDefault(); 461 | 462 | // assert 463 | Assert.NotNull(brokenRule); 464 | Assert.Equal("MaxCount", brokenRule.Rule); 465 | Assert.Equal("IEnumerable", brokenRule.Key); 466 | Assert.Equal("Collection count cannot be greater than 1.", brokenRule.Message); 467 | } 468 | 469 | [Fact] 470 | public void MaxCount_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToMaxCount() 471 | { 472 | // arrange 473 | var validator = new ValidatorBuilder>() 474 | .MaxCount(1) 475 | .Build(); 476 | 477 | // act 478 | var result = validator.Validate(new[] { "hello" }); 479 | 480 | // assert 481 | Assert.Empty(result.BrokenRules); 482 | } 483 | 484 | [Fact] 485 | public void MaxCount_ShouldNotAddBrokenRule_WhenCollectionCount_LessThanMaxCount() 486 | { 487 | // arrange 488 | var validator = new ValidatorBuilder>() 489 | .MaxCount(1) 490 | .Build(); 491 | 492 | // act 493 | var result = validator.Validate(Array.Empty()); 494 | 495 | // assert 496 | Assert.Empty(result.BrokenRules); 497 | } 498 | 499 | [Fact] 500 | public void MaxCount_ShouldPassKeyToBrokenRule_WhenKeyProvided() 501 | { 502 | // arrange 503 | var validator = new ValidatorBuilder>() 504 | .MaxCount(1, "test") 505 | .Build(); 506 | 507 | // act 508 | var result = validator.Validate(new List(new[] { "test", "hello" })); 509 | var brokenRule = result.BrokenRules.FirstOrDefault(); 510 | 511 | // assert 512 | Assert.Equal("test", brokenRule.Key); 513 | } 514 | 515 | [Fact] 516 | public void MaxCount_ShouldPassMessageToBrokenRule_WhenMessageProvided() 517 | { 518 | // arrange 519 | var validator = new ValidatorBuilder>() 520 | .MaxCount(1, message: "test") 521 | .Build(); 522 | 523 | // act 524 | var result = validator.Validate(new List(new[] { "test", "hello" })); 525 | var brokenRule = result.BrokenRules.FirstOrDefault(); 526 | 527 | // assert 528 | Assert.Equal("test", brokenRule.Message); 529 | } 530 | 531 | [Fact] 532 | public void MaxCountFor_ThrowsException_WhenBuilderIsNull() 533 | { 534 | Assert.Throws("builder", () => 535 | { 536 | ValidatorBuilderExtensions.MaxCount(null, null, 0); 537 | }); 538 | } 539 | 540 | [Fact] 541 | public void MaxCountFor_ThrowsException_WhenSelectorIsNull() 542 | { 543 | Assert.Throws("selector", () => 544 | { 545 | ValidatorBuilderExtensions.MaxCount(new ValidatorBuilder(), null, 0); 546 | }); 547 | } 548 | 549 | [Fact] 550 | public void MaxCountFor_ThrowsException_WhenCountLessThanZero() 551 | { 552 | Assert.Throws("count", () => 553 | { 554 | ValidatorBuilderExtensions.MaxCount(new ValidatorBuilder(), e => e.Skills, -1); 555 | }); 556 | } 557 | 558 | [Fact] 559 | public void MaxCountFor_ShouldAddBrokenRule_WhenCollectionCount_GreaterThanMaxCount() 560 | { 561 | // arrange 562 | var validator = new ValidatorBuilder() 563 | .MaxCount(e => e.Skills, 1) 564 | .Build(); 565 | 566 | // act 567 | var result = validator.Validate(new Employee { Skills = new[] { "test", "hello" } }); 568 | var brokenRule = result.BrokenRules.FirstOrDefault(); 569 | 570 | // assert 571 | Assert.NotNull(brokenRule); 572 | Assert.Equal("MaxCount", brokenRule.Rule); 573 | Assert.Equal("Skills", brokenRule.Key); 574 | Assert.Equal("Collection count cannot be greater than 1.", brokenRule.Message); 575 | } 576 | 577 | [Fact] 578 | public void MaxCountFor_ShouldNotAddBrokenRule_WhenCollectionCount_EqualToMaxCount() 579 | { 580 | // arrange 581 | var validator = new ValidatorBuilder() 582 | .MaxCount(e => e.Skills, 1) 583 | .Build(); 584 | 585 | // act 586 | var result = validator.Validate(new Employee { Skills = new[] { "hello" } }); 587 | 588 | // assert 589 | Assert.Empty(result.BrokenRules); 590 | } 591 | 592 | [Fact] 593 | public void MaxCountFor_ShouldNotAddBrokenRule_WhenCollectionCount_LessThanMaxCount() 594 | { 595 | // arrange 596 | var validator = new ValidatorBuilder() 597 | .MaxCount(e => e.Skills, 1) 598 | .Build(); 599 | 600 | // act 601 | var result = validator.Validate(new Employee { Skills = Array.Empty() }); 602 | 603 | // assert 604 | Assert.Empty(result.BrokenRules); 605 | } 606 | 607 | [Fact] 608 | public void MaxCountFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 609 | { 610 | // arrange 611 | var validator = new ValidatorBuilder() 612 | .MaxCount(e => e.Skills, 1, "test") 613 | .Build(); 614 | 615 | // act 616 | var result = validator.Validate(new Employee { Skills = new[] { "test", "hello" } }); 617 | var brokenRule = result.BrokenRules.FirstOrDefault(); 618 | 619 | // assert 620 | Assert.Equal("test", brokenRule.Key); 621 | } 622 | 623 | [Fact] 624 | public void MaxCountFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 625 | { 626 | // arrange 627 | var validator = new ValidatorBuilder() 628 | .MaxCount(e => e.Skills, 1, message: "test") 629 | .Build(); 630 | 631 | // act 632 | var result = validator.Validate(new Employee { Skills = new[] { "test", "hello" } }); 633 | var brokenRule = result.BrokenRules.FirstOrDefault(); 634 | 635 | // assert 636 | Assert.Equal("test", brokenRule.Message); 637 | } 638 | 639 | [Fact] 640 | public void Contains_ThrowsException_WhenBuilderIsNull() 641 | { 642 | Assert.Throws("builder", () => 643 | { 644 | ValidatorBuilderExtensions.Contains(null, 0); 645 | }); 646 | } 647 | 648 | [Fact] 649 | public void Contains_ThrowsException_WhenItemIsNull() 650 | { 651 | Assert.Throws("item", () => 652 | { 653 | ValidatorBuilderExtensions.Contains(new ValidatorBuilder>(), null); 654 | }); 655 | } 656 | 657 | [Fact] 658 | public void Contains_ShouldAddBrokenRule_WhenCollection_DoesNotContainItem() 659 | { 660 | // arrange 661 | var validator = new ValidatorBuilder>() 662 | .Contains(1) 663 | .Build(); 664 | 665 | // act 666 | var result = validator.Validate(new List()); 667 | var brokenRule = result.BrokenRules.FirstOrDefault(); 668 | 669 | // assert 670 | Assert.NotNull(brokenRule); 671 | Assert.Equal("Contains", brokenRule.Rule); 672 | Assert.Equal("IEnumerable", brokenRule.Key); 673 | Assert.Equal("Collection must contain item '1'.", brokenRule.Message); 674 | } 675 | 676 | [Fact] 677 | public void Contains_ShouldNotAddBrokenRule_WhenCollection_ContainsItem() 678 | { 679 | // arrange 680 | var validator = new ValidatorBuilder>() 681 | .Contains(2) 682 | .Build(); 683 | 684 | // act 685 | var result = validator.Validate(new[] { 1, 2, 3 }); 686 | 687 | // assert 688 | Assert.Empty(result.BrokenRules); 689 | } 690 | 691 | [Fact] 692 | public void Contains_ShouldPassKeyToBrokenRule_WhenKeyProvided() 693 | { 694 | // arrange 695 | var validator = new ValidatorBuilder>() 696 | .Contains(1, "test") 697 | .Build(); 698 | 699 | // act 700 | var result = validator.Validate(new List()); 701 | var brokenRule = result.BrokenRules.FirstOrDefault(); 702 | 703 | // assert 704 | Assert.Equal("test", brokenRule.Key); 705 | } 706 | 707 | [Fact] 708 | public void Contains_ShouldPassMessageToBrokenRule_WhenMessageProvided() 709 | { 710 | // arrange 711 | var validator = new ValidatorBuilder>() 712 | .Contains(1, message: "test") 713 | .Build(); 714 | 715 | // act 716 | var result = validator.Validate(new List()); 717 | var brokenRule = result.BrokenRules.FirstOrDefault(); 718 | 719 | // assert 720 | Assert.Equal("test", brokenRule.Message); 721 | } 722 | 723 | [Fact] 724 | public void ContainsFor_ThrowsException_WhenBuilderIsNull() 725 | { 726 | Assert.Throws("builder", () => 727 | { 728 | ValidatorBuilderExtensions.Contains(null, null, null); 729 | }); 730 | } 731 | 732 | [Fact] 733 | public void ContainsFor_ThrowsException_WhenSelectorIsNull() 734 | { 735 | Assert.Throws("selector", () => 736 | { 737 | ValidatorBuilderExtensions.Contains(new ValidatorBuilder(), null, null); 738 | }); 739 | } 740 | 741 | [Fact] 742 | public void ContainsFor_ThrowsException_WhenItemIsNull() 743 | { 744 | Assert.Throws("item", () => 745 | { 746 | ValidatorBuilderExtensions.Contains(new ValidatorBuilder(), e => e.Skills, null); 747 | }); 748 | } 749 | 750 | [Fact] 751 | public void ContainsFor_ShouldAddBrokenRule_WhenCollection_DoesNotContainItem() 752 | { 753 | // arrange 754 | var validator = new ValidatorBuilder() 755 | .Contains(e => e.Skills, "test") 756 | .Build(); 757 | 758 | // act 759 | var result = validator.Validate(new Employee()); 760 | var brokenRule = result.BrokenRules.FirstOrDefault(); 761 | 762 | // assert 763 | Assert.NotNull(brokenRule); 764 | Assert.Equal("Contains", brokenRule.Rule); 765 | Assert.Equal("Skills", brokenRule.Key); 766 | Assert.Equal("Collection must contain item 'test'.", brokenRule.Message); 767 | } 768 | 769 | [Fact] 770 | public void ContainsFor_ShouldNotAddBrokenRule_WhenCollection_ContainsItem() 771 | { 772 | // arrange 773 | var validator = new ValidatorBuilder() 774 | .Contains(e => e.Skills, "test") 775 | .Build(); 776 | 777 | // act 778 | var result = validator.Validate(new Employee { Skills = new[] { "test" } }); 779 | 780 | // assert 781 | Assert.Empty(result.BrokenRules); 782 | } 783 | 784 | [Fact] 785 | public void ContainsFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 786 | { 787 | // arrange 788 | var validator = new ValidatorBuilder() 789 | .Contains(e => e.Skills, "test", "test") 790 | .Build(); 791 | 792 | // act 793 | var result = validator.Validate(new Employee()); 794 | var brokenRule = result.BrokenRules.FirstOrDefault(); 795 | 796 | // assert 797 | Assert.Equal("test", brokenRule.Key); 798 | } 799 | 800 | [Fact] 801 | public void ContainsFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 802 | { 803 | // arrange 804 | var validator = new ValidatorBuilder() 805 | .Contains(e => e.Skills, "test", message: "test") 806 | .Build(); 807 | 808 | // act 809 | var result = validator.Validate(new Employee()); 810 | var brokenRule = result.BrokenRules.FirstOrDefault(); 811 | 812 | // assert 813 | Assert.Equal("test", brokenRule.Message); 814 | } 815 | } 816 | } -------------------------------------------------------------------------------- /src/Validatum/test/ValidatorBuilderExtensions.Common.Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Xunit; 4 | 5 | namespace Validatum.Tests 6 | { 7 | public class ValidatorBuilderCommonExtensionsTests 8 | { 9 | [Fact] 10 | public void NotNull_ThrowsException_WhenBuilderIsNull() 11 | { 12 | Assert.Throws("builder", () => 13 | { 14 | ValidatorBuilderExtensions.NotNull(null); 15 | }); 16 | } 17 | 18 | [Fact] 19 | public void NotNull_ShouldAddBrokenRule_WhenValueIsNull() 20 | { 21 | // arrange 22 | var validator = new ValidatorBuilder() 23 | .NotNull() 24 | .Build(); 25 | 26 | // act 27 | var result = validator.Validate(null); 28 | var brokenRule = result.BrokenRules.FirstOrDefault(); 29 | 30 | // assert 31 | Assert.NotNull(brokenRule); 32 | Assert.Equal("NotNull", brokenRule.Rule); 33 | Assert.Equal("Employee", brokenRule.Key); 34 | Assert.Equal("Value cannot be null.", brokenRule.Message); 35 | } 36 | 37 | [Fact] 38 | public void NotNull_ShouldNotAddBrokenRule_WhenValueIsNotNull() 39 | { 40 | // arrange 41 | var validator = new ValidatorBuilder() 42 | .NotNull() 43 | .Build(); 44 | 45 | // act 46 | var result = validator.Validate(new Employee()); 47 | 48 | // assert 49 | Assert.Empty(result.BrokenRules); 50 | } 51 | 52 | [Fact] 53 | public void NotNull_ShouldPassKeyToBrokenRule_WhenKeyProvided() 54 | { 55 | // arrange 56 | var validator = new ValidatorBuilder() 57 | .NotNull("test") 58 | .Build(); 59 | 60 | // act 61 | var result = validator.Validate(null); 62 | var brokenRule = result.BrokenRules.FirstOrDefault(); 63 | 64 | // assert 65 | Assert.Equal("test", brokenRule.Key); 66 | } 67 | 68 | [Fact] 69 | public void NotNull_ShouldPassMessageToBrokenRule_WhenMessageProvided() 70 | { 71 | // arrange 72 | var validator = new ValidatorBuilder() 73 | .NotNull(message: "test") 74 | .Build(); 75 | 76 | // act 77 | var result = validator.Validate(null); 78 | var brokenRule = result.BrokenRules.FirstOrDefault(); 79 | 80 | // assert 81 | Assert.Equal("test", brokenRule.Message); 82 | } 83 | 84 | [Fact] 85 | public void NotNullFor_ThrowsException_WhenBuilderIsNull() 86 | { 87 | Assert.Throws("builder", () => 88 | { 89 | ValidatorBuilderExtensions.NotNull(null, null); 90 | }); 91 | } 92 | 93 | [Fact] 94 | public void NotNullFor_ThrowsException_WhenSelectorIsNull() 95 | { 96 | Assert.Throws("selector", () => 97 | { 98 | ValidatorBuilderExtensions.NotNull(new ValidatorBuilder(), null); 99 | }); 100 | } 101 | 102 | [Fact] 103 | public void NotNullFor_ShouldAddBrokenRule_WhenValueIsNull() 104 | { 105 | // arrange 106 | var validator = new ValidatorBuilder() 107 | .NotNull(e => e.Employer.Name) 108 | .Build(); 109 | 110 | // act 111 | var result = validator.Validate(new Employee 112 | { 113 | FirstName = "John", 114 | Employer = new Company { Id = 5 } 115 | }); 116 | var brokenRule = result.BrokenRules.FirstOrDefault(); 117 | 118 | // assert 119 | Assert.NotNull(brokenRule); 120 | Assert.Equal("NotNull", brokenRule.Rule); 121 | Assert.Equal("Employer.Name", brokenRule.Key); 122 | Assert.Equal("Value cannot be null.", brokenRule.Message); 123 | } 124 | 125 | [Fact] 126 | public void NotNullFor_ShouldNotAddBrokenRule_WhenValueIsNotNull() 127 | { 128 | // arrange 129 | var validator = new ValidatorBuilder() 130 | .NotNull(e => e.Employer.Name) 131 | .Build(); 132 | 133 | // act 134 | var result = validator.Validate(new Employee 135 | { 136 | FirstName = "John", 137 | Employer = new Company { Id = 5, Name = "Acme Inc." } 138 | }); 139 | 140 | // assert 141 | Assert.Empty(result.BrokenRules); 142 | } 143 | 144 | [Fact] 145 | public void NotNullFor_ShouldUseExpressionMemberName_AsKeyInBrokenRule_WhenKeyNotProvided() 146 | { 147 | // arrange 148 | var validator = new ValidatorBuilder() 149 | .NotNull(e => e.Employer.Name) 150 | .Build(); 151 | 152 | // act 153 | var result = validator.Validate(new Employee 154 | { 155 | FirstName = "John", 156 | Employer = new Company { Id = 5 } 157 | }); 158 | var brokenRule = result.BrokenRules.FirstOrDefault(); 159 | 160 | // assert 161 | Assert.NotNull(brokenRule); 162 | Assert.Equal("Employer.Name", brokenRule.Key); 163 | } 164 | 165 | [Fact] 166 | public void NotNullFor_ShouldUseKey_AsKeyInBrokenRule_WhenKeyProvided() 167 | { 168 | // arrange 169 | var validator = new ValidatorBuilder() 170 | .NotNull(e => e.Employer.Name, key: "test") 171 | .Build(); 172 | 173 | // act 174 | var result = validator.Validate(new Employee 175 | { 176 | FirstName = "John", 177 | Employer = new Company { Id = 5 } 178 | }); 179 | var brokenRule = result.BrokenRules.FirstOrDefault(); 180 | 181 | // assert 182 | Assert.NotNull(brokenRule); 183 | Assert.Equal("test", brokenRule.Key); 184 | } 185 | 186 | [Fact] 187 | public void NotNullFor_ShouldUseMessage_AsErrorInBrokenRule_WhenMessageProvided() 188 | { 189 | // arrange 190 | var validator = new ValidatorBuilder() 191 | .NotNull(e => e.Employer.Name, message: "test") 192 | .Build(); 193 | 194 | // act 195 | var result = validator.Validate(new Employee 196 | { 197 | FirstName = "John", 198 | Employer = new Company { Id = 5 } 199 | }); 200 | var brokenRule = result.BrokenRules.FirstOrDefault(); 201 | 202 | // assert 203 | Assert.NotNull(brokenRule); 204 | Assert.Equal("test", brokenRule.Message); 205 | } 206 | 207 | [Fact] 208 | public void NotNullFor_ShouldNotAddBrokenRule_WhenTargetIsNotNull() 209 | { 210 | // arrange 211 | var validator = new ValidatorBuilder() 212 | .NotNull(e => e.Employer.Name) 213 | .Build(); 214 | 215 | // act 216 | var result = validator.Validate(new Employee 217 | { 218 | FirstName = "John", 219 | Employer = new Company { Id = 5, Name = "Acme Inc." } 220 | }); 221 | 222 | // assert 223 | Assert.True(result.IsValid); 224 | Assert.Empty(result.BrokenRules); 225 | } 226 | 227 | [Fact] 228 | public void Null_ThrowsException_WhenBuilderIsNull() 229 | { 230 | Assert.Throws("builder", () => 231 | { 232 | ValidatorBuilderExtensions.Null(null); 233 | }); 234 | } 235 | 236 | [Fact] 237 | public void Null_ShouldAddBrokenRule_WhenValueIsNotNull() 238 | { 239 | // arrange 240 | var validator = new ValidatorBuilder() 241 | .Null() 242 | .Build(); 243 | 244 | // act 245 | var result = validator.Validate(new Employee()); 246 | var brokenRule = result.BrokenRules.FirstOrDefault(); 247 | 248 | // assert 249 | Assert.NotNull(brokenRule); 250 | Assert.Equal("Null", brokenRule.Rule); 251 | Assert.Equal("Employee", brokenRule.Key); 252 | Assert.Equal("Value must be null.", brokenRule.Message); 253 | } 254 | 255 | [Fact] 256 | public void Null_ShouldNotAddBrokenRule_WhenValueIsNull() 257 | { 258 | // arrange 259 | var validator = new ValidatorBuilder() 260 | .Null() 261 | .Build(); 262 | 263 | // act 264 | var result = validator.Validate(null); 265 | 266 | // assert 267 | Assert.Empty(result.BrokenRules); 268 | } 269 | 270 | [Fact] 271 | public void Null_ShouldPassKeyToBrokenRule_WhenKeyProvided() 272 | { 273 | // arrange 274 | var validator = new ValidatorBuilder() 275 | .Null("test") 276 | .Build(); 277 | 278 | // act 279 | var result = validator.Validate(new Employee()); 280 | var brokenRule = result.BrokenRules.FirstOrDefault(); 281 | 282 | // assert 283 | Assert.Equal("test", brokenRule.Key); 284 | } 285 | 286 | [Fact] 287 | public void Null_ShouldPassMessageToBrokenRule_WhenMessageProvided() 288 | { 289 | // arrange 290 | var validator = new ValidatorBuilder() 291 | .Null(message: "test") 292 | .Build(); 293 | 294 | // act 295 | var result = validator.Validate(new Employee()); 296 | var brokenRule = result.BrokenRules.FirstOrDefault(); 297 | 298 | // assert 299 | Assert.Equal("test", brokenRule.Message); 300 | } 301 | 302 | [Fact] 303 | public void NullFor_ThrowsException_WhenBuilderIsNull() 304 | { 305 | Assert.Throws("builder", () => 306 | { 307 | ValidatorBuilderExtensions.Null(null, null); 308 | }); 309 | } 310 | 311 | [Fact] 312 | public void NullFor_ThrowsException_WhenSelectorIsNull() 313 | { 314 | Assert.Throws("selector", () => 315 | { 316 | ValidatorBuilderExtensions.Null(new ValidatorBuilder(), null); 317 | }); 318 | } 319 | 320 | [Fact] 321 | public void NullFor_ShouldAddBrokenRule_WhenValueIsNotNull() 322 | { 323 | // arrange 324 | var validator = new ValidatorBuilder() 325 | .Null(e => e.Employer.Name) 326 | .Build(); 327 | 328 | // act 329 | var result = validator.Validate(new Employee 330 | { 331 | Employer = new Company { Name = "Acme Inc." } 332 | }); 333 | var brokenRule = result.BrokenRules.FirstOrDefault(); 334 | 335 | // assert 336 | Assert.NotNull(brokenRule); 337 | Assert.Equal("Null", brokenRule.Rule); 338 | Assert.Equal("Employer.Name", brokenRule.Key); 339 | Assert.Equal("Value must be null.", brokenRule.Message); 340 | } 341 | 342 | [Fact] 343 | public void NullFor_ShouldNotAddBrokenRule_WhenTargetIsNull() 344 | { 345 | // arrange 346 | var validator = new ValidatorBuilder() 347 | .Null(e => e.Employer.Name) 348 | .Build(); 349 | 350 | // act 351 | var result = validator.Validate(new Employee 352 | { 353 | FirstName = "John", 354 | Employer = new Company { Id = 5 } 355 | }); 356 | 357 | // assert 358 | Assert.True(result.IsValid); 359 | Assert.Empty(result.BrokenRules); 360 | } 361 | 362 | [Fact] 363 | public void NullFor_ShouldUseExpressionMemberName_AsKeyInBrokenRule_WhenKeyNotProvided() 364 | { 365 | // arrange 366 | var validator = new ValidatorBuilder() 367 | .Null(e => e.Employer.Name) 368 | .Build(); 369 | 370 | // act 371 | var result = validator.Validate(new Employee 372 | { 373 | FirstName = "John", 374 | Employer = new Company { Id = 5, Name = "Acme Inc." } 375 | }); 376 | var brokenRule = result.BrokenRules.FirstOrDefault(); 377 | 378 | // assert 379 | Assert.NotNull(brokenRule); 380 | Assert.Equal("Employer.Name", brokenRule.Key); 381 | } 382 | 383 | [Fact] 384 | public void NullFor_ShouldUseKey_AsKeyInBrokenRule_WhenKeyProvided() 385 | { 386 | // arrange 387 | var validator = new ValidatorBuilder() 388 | .Null(e => e.Employer.Name, key: "test") 389 | .Build(); 390 | 391 | // act 392 | var result = validator.Validate(new Employee 393 | { 394 | FirstName = "John", 395 | Employer = new Company { Id = 5, Name = "Acme Inc." } 396 | }); 397 | var brokenRule = result.BrokenRules.FirstOrDefault(); 398 | 399 | // assert 400 | Assert.NotNull(brokenRule); 401 | Assert.Equal("test", brokenRule.Key); 402 | } 403 | 404 | [Fact] 405 | public void NullFor_ShouldUseMessage_InBrokenRule_WhenMessageProvided() 406 | { 407 | // arrange 408 | var validator = new ValidatorBuilder() 409 | .Null(e => e.Employer.Name, message: "test") 410 | .Build(); 411 | 412 | // act 413 | var result = validator.Validate(new Employee 414 | { 415 | FirstName = "John", 416 | Employer = new Company { Id = 5, Name = "Acme Inc." } 417 | }); 418 | var brokenRule = result.BrokenRules.FirstOrDefault(); 419 | 420 | // assert 421 | Assert.NotNull(brokenRule); 422 | Assert.Equal("test", brokenRule.Message); 423 | } 424 | 425 | [Fact] 426 | public void Equal_ThrowsException_WhenBuilderIsNull() 427 | { 428 | Assert.Throws("builder", () => 429 | { 430 | ValidatorBuilderExtensions.Equal(null, null); 431 | }); 432 | } 433 | 434 | [Fact] 435 | public void Equal_ShouldAddBrokenRule_WhenValueIsNotEqual() 436 | { 437 | // arrange 438 | var validator = new ValidatorBuilder() 439 | .Equal("test") 440 | .Build(); 441 | 442 | // act 443 | var result = validator.Validate("hello"); 444 | var brokenRule = result.BrokenRules.FirstOrDefault(); 445 | 446 | // assert 447 | Assert.NotNull(brokenRule); 448 | Assert.Equal("Equal", brokenRule.Rule); 449 | Assert.Equal("String", brokenRule.Key); 450 | Assert.Equal("Value must equal 'test'.", brokenRule.Message); 451 | } 452 | 453 | [Fact] 454 | public void Equal_ShouldAddBrokenRule_WhenValueIsNotNullAndOtherIsNull() 455 | { 456 | // arrange 457 | var validator = new ValidatorBuilder() 458 | .Equal(null) 459 | .Build(); 460 | 461 | // act 462 | var result = validator.Validate("hello"); 463 | var brokenRule = result.BrokenRules.FirstOrDefault(); 464 | 465 | // assert 466 | Assert.NotNull(brokenRule); 467 | Assert.Equal("Equal", brokenRule.Rule); 468 | Assert.Equal("String", brokenRule.Key); 469 | Assert.Equal("Value must equal 'null'.", brokenRule.Message); 470 | } 471 | 472 | [Fact] 473 | public void Equal_ShouldNotAddBrokenRule_WhenValueIsEqual() 474 | { 475 | // arrange 476 | var validator = new ValidatorBuilder() 477 | .Equal("test") 478 | .Build(); 479 | 480 | // act 481 | var result = validator.Validate("test"); 482 | 483 | // assert 484 | Assert.Empty(result.BrokenRules); 485 | } 486 | 487 | [Fact] 488 | public void Equal_ShouldNotAddBrokenRule_WhenBothValuesAreNull() 489 | { 490 | // arrange 491 | var validator = new ValidatorBuilder() 492 | .Equal(null) 493 | .Build(); 494 | 495 | // act 496 | var result = validator.Validate(null); 497 | 498 | // assert 499 | Assert.Empty(result.BrokenRules); 500 | } 501 | 502 | [Fact] 503 | public void Equal_ShouldPassKeyToBrokenRule_WhenKeyProvided() 504 | { 505 | // arrange 506 | var validator = new ValidatorBuilder() 507 | .Equal("test", "test") 508 | .Build(); 509 | 510 | // act 511 | var result = validator.Validate("hello"); 512 | var brokenRule = result.BrokenRules.FirstOrDefault(); 513 | 514 | // assert 515 | Assert.Equal("test", brokenRule.Key); 516 | } 517 | 518 | [Fact] 519 | public void Equal_ShouldPassMessageToBrokenRule_WhenMessageProvided() 520 | { 521 | // arrange 522 | var validator = new ValidatorBuilder() 523 | .Equal("test", message: "test") 524 | .Build(); 525 | 526 | // act 527 | var result = validator.Validate("hello"); 528 | var brokenRule = result.BrokenRules.FirstOrDefault(); 529 | 530 | // assert 531 | Assert.Equal("test", brokenRule.Message); 532 | } 533 | 534 | [Fact] 535 | public void EqualFor_ThrowsException_WhenBuilderIsNull() 536 | { 537 | Assert.Throws("builder", () => 538 | { 539 | ValidatorBuilderExtensions.Equal(null, null, null); 540 | }); 541 | } 542 | 543 | [Fact] 544 | public void EqualFor_ThrowsException_WhenSelectorIsNull() 545 | { 546 | Assert.Throws("selector", () => 547 | { 548 | ValidatorBuilderExtensions.Equal(new ValidatorBuilder(), null, null); 549 | }); 550 | } 551 | 552 | [Fact] 553 | public void EqualFor_ShouldAddBrokenRule_WhenValueIsNotEqual() 554 | { 555 | // arrange 556 | var validator = new ValidatorBuilder() 557 | .Equal(e => e.LastName, "Simpson") 558 | .Build(); 559 | 560 | // act 561 | var result = validator.Validate(new Employee { LastName = "Cruz" }); 562 | var brokenRule = result.BrokenRules.FirstOrDefault(); 563 | 564 | // assert 565 | Assert.NotNull(brokenRule); 566 | Assert.Equal("Equal", brokenRule.Rule); 567 | Assert.Equal("LastName", brokenRule.Key); 568 | Assert.Equal("Value must equal 'Simpson'.", brokenRule.Message); 569 | } 570 | 571 | [Fact] 572 | public void EqualFor_ShouldAddBrokenRule_WhenValueIsNotNullAndOtherIsNull() 573 | { 574 | // arrange 575 | var validator = new ValidatorBuilder() 576 | .Equal(e => e.LastName, null) 577 | .Build(); 578 | 579 | // act 580 | var result = validator.Validate(new Employee { LastName = "Cruz" }); 581 | var brokenRule = result.BrokenRules.FirstOrDefault(); 582 | 583 | // assert 584 | Assert.NotNull(brokenRule); 585 | Assert.Equal("Equal", brokenRule.Rule); 586 | Assert.Equal("LastName", brokenRule.Key); 587 | Assert.Equal("Value must equal 'null'.", brokenRule.Message); 588 | } 589 | 590 | [Fact] 591 | public void EqualFor_ShouldNotAddBrokenRule_WhenValueIsEqual() 592 | { 593 | // arrange 594 | var validator = new ValidatorBuilder() 595 | .Equal(e => e.LastName, "Smith") 596 | .Build(); 597 | 598 | // act 599 | var result = validator.Validate(new Employee { LastName = "Smith" }); 600 | 601 | // assert 602 | Assert.Empty(result.BrokenRules); 603 | } 604 | 605 | [Fact] 606 | public void EqualFor_ShouldNotAddBrokenRule_WhenBothValuesAreNull() 607 | { 608 | // arrange 609 | var validator = new ValidatorBuilder() 610 | .Equal(e => e.LastName, null) 611 | .Build(); 612 | 613 | // act 614 | var result = validator.Validate(new Employee()); 615 | 616 | // assert 617 | Assert.Empty(result.BrokenRules); 618 | } 619 | 620 | [Fact] 621 | public void EqualFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 622 | { 623 | // arrange 624 | var validator = new ValidatorBuilder() 625 | .Equal(e => e.LastName, "test", "test") 626 | .Build(); 627 | 628 | // act 629 | var result = validator.Validate(new Employee()); 630 | var brokenRule = result.BrokenRules.FirstOrDefault(); 631 | 632 | // assert 633 | Assert.Equal("test", brokenRule.Key); 634 | } 635 | 636 | [Fact] 637 | public void EqualFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 638 | { 639 | // arrange 640 | var validator = new ValidatorBuilder() 641 | .Equal(e => e.LastName, "test", message: "test") 642 | .Build(); 643 | 644 | // act 645 | var result = validator.Validate(new Employee()); 646 | var brokenRule = result.BrokenRules.FirstOrDefault(); 647 | 648 | // assert 649 | Assert.Equal("test", brokenRule.Message); 650 | } 651 | 652 | [Fact] 653 | public void NotEqual_ThrowsException_WhenBuilderIsNull() 654 | { 655 | Assert.Throws("builder", () => 656 | { 657 | ValidatorBuilderExtensions.NotEqual(null, null); 658 | }); 659 | } 660 | 661 | [Fact] 662 | public void NotEqual_ShouldAddBrokenRule_WhenValueIsEqual() 663 | { 664 | // arrange 665 | var validator = new ValidatorBuilder() 666 | .NotEqual("test") 667 | .Build(); 668 | 669 | // act 670 | var result = validator.Validate("test"); 671 | var brokenRule = result.BrokenRules.FirstOrDefault(); 672 | 673 | // assert 674 | Assert.NotNull(brokenRule); 675 | Assert.Equal("NotEqual", brokenRule.Rule); 676 | Assert.Equal("String", brokenRule.Key); 677 | Assert.Equal("Value must not equal 'test'.", brokenRule.Message); 678 | } 679 | 680 | [Fact] 681 | public void NotEqual_ShouldNotAddBrokenRule_WhenValueIsNotEqual() 682 | { 683 | // arrange 684 | var validator = new ValidatorBuilder() 685 | .NotEqual("test") 686 | .Build(); 687 | 688 | // act 689 | var result = validator.Validate("hello"); 690 | 691 | // assert 692 | Assert.Empty(result.BrokenRules); 693 | } 694 | 695 | [Fact] 696 | public void NotEqual_ShouldAddBrokenRule_WhenBothValuesAreNull() 697 | { 698 | // arrange 699 | var validator = new ValidatorBuilder() 700 | .NotEqual(null) 701 | .Build(); 702 | 703 | // act 704 | var result = validator.Validate(null); 705 | 706 | // assert 707 | Assert.NotEmpty(result.BrokenRules); 708 | } 709 | 710 | [Fact] 711 | public void NotEqual_ShouldPassKeyToBrokenRule_WhenKeyProvided() 712 | { 713 | // arrange 714 | var validator = new ValidatorBuilder() 715 | .NotEqual("test", "test") 716 | .Build(); 717 | 718 | // act 719 | var result = validator.Validate("test"); 720 | var brokenRule = result.BrokenRules.FirstOrDefault(); 721 | 722 | // assert 723 | Assert.Equal("test", brokenRule.Key); 724 | } 725 | 726 | [Fact] 727 | public void NotEqual_ShouldPassMessageToBrokenRule_WhenMessageProvided() 728 | { 729 | // arrange 730 | var validator = new ValidatorBuilder() 731 | .NotEqual("test", message: "test") 732 | .Build(); 733 | 734 | // act 735 | var result = validator.Validate("test"); 736 | var brokenRule = result.BrokenRules.FirstOrDefault(); 737 | 738 | // assert 739 | Assert.Equal("test", brokenRule.Message); 740 | } 741 | 742 | [Fact] 743 | public void NotEqualFor_ThrowsException_WhenBuilderIsNull() 744 | { 745 | Assert.Throws("builder", () => 746 | { 747 | ValidatorBuilderExtensions.NotEqual(null, null, null); 748 | }); 749 | } 750 | 751 | [Fact] 752 | public void NotEqualFor_ThrowsException_WhenSelectorIsNull() 753 | { 754 | Assert.Throws("selector", () => 755 | { 756 | ValidatorBuilderExtensions.NotEqual(new ValidatorBuilder(), null, null); 757 | }); 758 | } 759 | 760 | [Fact] 761 | public void NotEqualFor_ShouldAddBrokenRule_WhenValueIsEqual() 762 | { 763 | // arrange 764 | var validator = new ValidatorBuilder() 765 | .NotEqual(e => e.Salary, 50000) 766 | .Build(); 767 | 768 | // act 769 | var result = validator.Validate(new Employee { Salary = 50000 }); 770 | var brokenRule = result.BrokenRules.FirstOrDefault(); 771 | 772 | // assert 773 | Assert.NotNull(brokenRule); 774 | Assert.Equal("NotEqual", brokenRule.Rule); 775 | Assert.Equal("Salary", brokenRule.Key); 776 | Assert.Equal("Value must not equal '50000'.", brokenRule.Message); 777 | } 778 | 779 | [Fact] 780 | public void NotEqualFor_ShouldNotAddBrokenRule_WhenValueIsNotEqual() 781 | { 782 | // arrange 783 | var validator = new ValidatorBuilder() 784 | .NotEqual(e => e.Salary, 50000) 785 | .Build(); 786 | 787 | // act 788 | var result = validator.Validate(new Employee { Salary = 60000 }); 789 | 790 | // assert 791 | Assert.Empty(result.BrokenRules); 792 | } 793 | 794 | [Fact] 795 | public void NotEqualFor_ShouldAddBrokenRule_WhenBothValuesAreNull() 796 | { 797 | // arrange 798 | var validator = new ValidatorBuilder() 799 | .NotEqual(e => e.FirstName, null) 800 | .Build(); 801 | 802 | // act 803 | var result = validator.Validate(new Employee()); 804 | 805 | // assert 806 | Assert.NotEmpty(result.BrokenRules); 807 | } 808 | 809 | [Fact] 810 | public void NotEqualFor_ShouldPassKeyToBrokenRule_WhenKeyProvided() 811 | { 812 | // arrange 813 | var validator = new ValidatorBuilder() 814 | .NotEqual(e => e.LastName, "Simpson", "test") 815 | .Build(); 816 | 817 | // act 818 | var result = validator.Validate(new Employee { LastName = "Simpson" }); 819 | var brokenRule = result.BrokenRules.FirstOrDefault(); 820 | 821 | // assert 822 | Assert.Equal("test", brokenRule.Key); 823 | } 824 | 825 | [Fact] 826 | public void NotEqualFor_ShouldPassMessageToBrokenRule_WhenMessageProvided() 827 | { 828 | // arrange 829 | var validator = new ValidatorBuilder() 830 | .NotEqual(e => e.LastName, "Simpson", message: "test") 831 | .Build(); 832 | 833 | // act 834 | var result = validator.Validate(new Employee { LastName = "Simpson" }); 835 | var brokenRule = result.BrokenRules.FirstOrDefault(); 836 | 837 | // assert 838 | Assert.Equal("test", brokenRule.Message); 839 | } 840 | } 841 | } -------------------------------------------------------------------------------- /src/Validatum/test/ValidatorBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Xunit; 4 | 5 | namespace Validatum.Tests 6 | { 7 | public class ValidatorBuilderTests 8 | { 9 | [Fact] 10 | public void Build_ReturnsValidatorInstance() 11 | { 12 | // arrange 13 | var builder = new ValidatorBuilder(); 14 | 15 | // act 16 | var validator = builder.Build(); 17 | 18 | // assert 19 | Assert.NotNull(validator); 20 | } 21 | 22 | [Fact] 23 | public void Build_ShouldSetLabelToTypeName_WhenLabelNotProvided() 24 | { 25 | // arrange 26 | var builder = new ValidatorBuilder(); 27 | 28 | // act 29 | var validator = builder.Build(); 30 | 31 | // assert 32 | Assert.Equal(typeof(Employee).Name, validator.Label); 33 | } 34 | 35 | [Fact] 36 | public void Build_ShouldSetLabelOnValidator_WhenLabelProvided() 37 | { 38 | // arrange 39 | var builder = new ValidatorBuilder(); 40 | 41 | // act 42 | var validator = builder.Build("test"); 43 | 44 | // assert 45 | Assert.Equal("test", validator.Label); 46 | } 47 | 48 | [Fact] 49 | public void Build_ShouldOnlyBuildTheDelegateChainOnce() 50 | { 51 | // arrange 52 | var builder = new ValidatorBuilder(); 53 | 54 | // act 55 | var validator1 = builder.Build("test1"); 56 | var validator2 = builder.Build("test2"); 57 | 58 | // assert 59 | Assert.Same(validator1, validator2); 60 | Assert.Equal("test1", validator2.Label); 61 | Assert.Equal(validator1.Label, validator2.Label); 62 | } 63 | 64 | [Fact] 65 | public void With_ShouldThrowException_WhenValidatorDelegateIsNull() 66 | { 67 | Assert.Throws("func", () => 68 | { 69 | new ValidatorBuilder() 70 | .With(null) 71 | .Build(); 72 | }); 73 | } 74 | 75 | [Fact] 76 | public void With_ShouldAddDelegateToChain() 77 | { 78 | // arrange 79 | int callCount = 0; 80 | var builder = new ValidatorBuilder() 81 | .With(ctx => 82 | { 83 | callCount++; 84 | }) 85 | .With(ctx => 86 | { 87 | callCount++; 88 | }); 89 | var validator = builder.Build(); 90 | 91 | // act 92 | var result = validator.Validate("test"); 93 | 94 | // assert 95 | Assert.Equal(2, callCount); 96 | } 97 | 98 | [Fact] 99 | public void With_ShouldThrowValidationException_WhenThrowWhenInvalidIsTrue() 100 | { 101 | // arrange 102 | var validator = new ValidatorBuilder() 103 | .With(ctx => 104 | { 105 | ctx.AddBrokenRule("test1", "test1", "test1"); 106 | }) 107 | .With(ctx => 108 | { 109 | ctx.AddBrokenRule("test2", "test2", "test2"); 110 | }) 111 | .Build(); 112 | 113 | // assert 114 | Assert.Throws(() => 115 | { 116 | try 117 | { 118 | // act 119 | validator.Validate("test", new ValidationOptions { ThrowWhenInvalid = true }); 120 | } 121 | catch (ValidationException ex) 122 | { 123 | Assert.Equal(2, ex.BrokenRules.Count()); 124 | throw ex; 125 | } 126 | }); 127 | } 128 | 129 | [Fact] 130 | public void With_ShouldHaltExecution_WhenStopWhenInvalidIsTrue() 131 | { 132 | var secondFuncCalled = false; 133 | 134 | // arrange 135 | var validator = new ValidatorBuilder() 136 | .With(ctx => 137 | { 138 | ctx.AddBrokenRule("test1", "test1", "test1"); 139 | }) 140 | .With(ctx => 141 | { 142 | secondFuncCalled = true; 143 | ctx.AddBrokenRule("test2", "test2", "test2"); 144 | }) 145 | .Build(); 146 | 147 | // assert 148 | var result = validator.Validate("test", new ValidationOptions { StopWhenInvalid = true }); 149 | 150 | // act 151 | Assert.False(secondFuncCalled); 152 | Assert.Single(result.BrokenRules); 153 | } 154 | 155 | [Fact] 156 | public void With_ShouldHaltExecutionAndThrowException_WhenStopWhenInvalidIsTrue_AndThrowWhenInvalidIsTrue() 157 | { 158 | var secondFuncCalled = false; 159 | 160 | // arrange 161 | var validator = new ValidatorBuilder() 162 | .With(ctx => 163 | { 164 | ctx.AddBrokenRule("test1", "test1", "test1"); 165 | }) 166 | .With(ctx => 167 | { 168 | secondFuncCalled = true; 169 | ctx.AddBrokenRule("test2", "test2", "test2"); 170 | }) 171 | .Build(); 172 | 173 | // assert 174 | Assert.Throws(() => 175 | { 176 | try 177 | { 178 | // act 179 | validator.Validate("test", new ValidationOptions { StopWhenInvalid = true, ThrowWhenInvalid = true }); 180 | } 181 | catch (ValidationException ex) 182 | { 183 | Assert.Single(ex.BrokenRules); 184 | throw ex; 185 | } 186 | }); 187 | 188 | Assert.False(secondFuncCalled); 189 | } 190 | 191 | [Fact] 192 | public void With_ShouldNotThrowException_WhenAddBrokenRuleForExceptionIsTrue_AndThrowWhenInvalidIsFalse() 193 | { 194 | // arrange 195 | var validator = new ValidatorBuilder() 196 | .With(ctx => 197 | { 198 | throw new FormatException("FormatException test"); 199 | }) 200 | .With(ctx => 201 | { 202 | throw new InvalidOperationException("InvalidOperationException test"); 203 | }) 204 | .Build(); 205 | 206 | // act 207 | var result = validator.Validate("test", new ValidationOptions { AddBrokenRuleForException = true, ThrowWhenInvalid = false }); 208 | var brokenRule1 = result.BrokenRules.FirstOrDefault(); 209 | var brokenRule2 = result.BrokenRules.LastOrDefault(); 210 | 211 | // assert 212 | Assert.Equal(2, result.BrokenRules.Count()); 213 | Assert.NotNull(brokenRule1); 214 | Assert.NotNull(brokenRule2); 215 | Assert.Equal("FormatException", brokenRule1.Rule); 216 | Assert.Equal("String", brokenRule1.Key); 217 | Assert.Equal("FormatException test", brokenRule1.Message); 218 | Assert.Equal("InvalidOperationException", brokenRule2.Rule); 219 | Assert.Equal("String", brokenRule2.Key); 220 | Assert.Equal("InvalidOperationException test", brokenRule2.Message); 221 | } 222 | 223 | [Fact] 224 | public void With_ShouldThrowValidationException_WhenUnhandledExceptionThrown_AndAddBrokenRuleForExceptionIsFalse() 225 | { 226 | // arrange 227 | var validator = new ValidatorBuilder() 228 | .With(ctx => 229 | { 230 | ctx.AddBrokenRule("test", "test", "test"); 231 | }) 232 | .With(ctx => 233 | { 234 | throw new InvalidOperationException(); 235 | }) 236 | .Build(); 237 | 238 | // assert 239 | Assert.Throws(() => 240 | { 241 | try 242 | { 243 | // act 244 | validator.Validate("test", new ValidationOptions { AddBrokenRuleForException = false }); 245 | } 246 | catch (ValidationException ex) 247 | { 248 | Assert.IsType(ex.InnerException); 249 | throw ex; 250 | } 251 | }); 252 | } 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/Validatum/test/Validatum.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | --------------------------------------------------------------------------------