├── .gitignore ├── LICENSE ├── README.md ├── source ├── Validators.Attributes.pas └── Validators.Engine.pas └── tests ├── BOU.pas ├── EntitiesValidatorsUnitTest.dpr ├── EntitiesValidatorsUnitTest.dproj ├── EntitiesValidatorsUnitTest.res ├── Validators.Custom.Tests.pas └── Validators.Properties.Tests.pas /.gitignore: -------------------------------------------------------------------------------- 1 | # Uncomment these types if you want even more clean repository. But be careful. 2 | # It can make harm to an existing project source. Read explanations below. 3 | # 4 | # Resource files are binaries containing manifest, project icon and version info. 5 | # They can not be viewed as text or compared by diff-tools. Consider replacing them with .rc files. 6 | #*.res 7 | # 8 | # Type library file (binary). In old Delphi versions it should be stored. 9 | # Since Delphi 2009 it is produced from .ridl file and can safely be ignored. 10 | #*.tlb 11 | # 12 | # Diagram Portfolio file. Used by the diagram editor up to Delphi 7. 13 | # Uncomment this if you are not using diagrams or use newer Delphi version. 14 | #*.ddp 15 | # 16 | # Visual LiveBindings file. Added in Delphi XE2. 17 | # Uncomment this if you are not using LiveBindings Designer. 18 | #*.vlb 19 | # 20 | # Deployment Manager configuration file for your project. Added in Delphi XE2. 21 | # Uncomment this if it is not mobile development and you do not use remote debug feature. 22 | #*.deployproj 23 | # 24 | # C++ object files produced when C/C++ Output file generation is configured. 25 | # Uncomment this if you are not using external objects (zlib library for example). 26 | #*.obj 27 | # 28 | 29 | # Delphi compiler-generated binaries (safe to delete) 30 | *.exe 31 | *.dll 32 | *.bpl 33 | *.bpi 34 | *.dcp 35 | *.so 36 | *.apk 37 | *.drc 38 | *.map 39 | *.dres 40 | *.rsm 41 | *.tds 42 | *.dcu 43 | *.lib 44 | *.a 45 | *.o 46 | *.ocx 47 | 48 | # Delphi autogenerated files (duplicated info) 49 | *.cfg 50 | *.hpp 51 | *Resource.rc 52 | 53 | # Delphi local files (user-specific info) 54 | *.local 55 | *.identcache 56 | *.projdata 57 | *.tvsconfig 58 | *.dsk 59 | 60 | # Delphi history and backups 61 | __history/ 62 | __recovery/ 63 | *.~* 64 | 65 | # Castalia statistics file (since XE7 Castalia is distributed with Delphi) 66 | *.stat 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Delphi Entities Validators 2 | 3 | Delphi Entities Validators is a microframework that provides an easy and ready-to-use interface for entities validation. 4 | 5 | ## How it works 6 | 7 | ### Simple Validation 8 | ```Delphi 9 | type 10 | TPersonValidator = class(TInterfacedObject, IValidator) 11 | public 12 | function Validate(aEntity: TPerson): IValidationResult; 13 | end; 14 | 15 | implementation 16 | 17 | function TPersonValidator.Validate(aEntity: TPerson): IValidationResult; 18 | var 19 | lIsValid: boolean; 20 | begin 21 | Result := TValidationResult.Create; 22 | lIsValid := not(aEntity.Firstname.IsEmpty or aEntity.Lastname.IsEmpty or aEntity.Email.IsEmpty); 23 | if not lIsValid then 24 | Result.BrokenRules := ['The fields Firstname, Lastname and Email are mandatory ']; 25 | end; 26 | 27 | ... 28 | 29 | lPersonValidator := TPersonValidator.Create; 30 | lValidationResult := lPersonValidator.Validate(lPerson); 31 | lValidationResult.IsValid; // returns a boolean that represents the success or failures validation 32 | lValidationResult.BrokenRules; // returns an array of string that represents the broken rules 33 | ``` 34 | 35 | ### Attributes Validation 36 | ```Delphi 37 | TPerson = class 38 | private 39 | FLastname: string; 40 | FFirstname: string; 41 | procedure SetFirstname(const Value: string); 42 | procedure SetLastname(const Value: string); 43 | public 44 | [RequiredValidation('AttributesValidation', 'Firstname is required')] 45 | [MaxLengthValidation('AttributesValidation', 'Firstname is too long', 8)] 46 | [MinLengthValidation('AttributesValidation', 'Firstname is too short', 4)] 47 | property Firstname: string read FFirstname write SetFirstname; 48 | [RequiredValidation('AttributesValidation', 'Firstname is required')] 49 | property Lastname: string read FLastname write SetLastname; 50 | end; 51 | 52 | ... 53 | 54 | lValidationResult := TValidationEngine.PropertyValidation(lPerson, 'AttributesValidation'); 55 | lValidationResult.IsValid; // returns a boolean that represents the success or failures validation 56 | lValidationResult.BrokenRules; // returns an array of string that represents the broken rules 57 | ``` 58 | ### Using container 59 | ```Delphi 60 | TPersonLoginValidator = class(TInterfacedObject, IValidator) 61 | public 62 | function Validate(aEntity: TPerson): IValidationResult; 63 | end; 64 | 65 | implementation 66 | 67 | function TPersonLoginValidator.Validate(aEntity: TPerson): IValidationResult; 68 | var 69 | lIsValid: boolean; 70 | begin 71 | Result := TValidationResult.Create; 72 | lIsValid := not(aEntity.Firstname.IsEmpty or aEntity.Lastname.IsEmpty or aEntity.Email.IsEmpty); 73 | if not lIsValid then 74 | Result.BrokenRules := ['The fields Firstname, Lastname and Email are mandatory ']; 75 | end; 76 | 77 | ... 78 | 79 | TValidationEngine.ValidationContainer.RegisterValidatorFor('PersonLogidValidation', TPersonLoginValidator.Create); 80 | lValidationResult := TValidationEngine.EntityValidation(lPerson,'PersonLoginValidation'); 81 | lValidationResult.IsValid; // returns a boolean that represents the success or failures validation 82 | lValidationResult.BrokenRules; // returns an array of string that represents the broken rules 83 | ``` 84 | -------------------------------------------------------------------------------- /source/Validators.Attributes.pas: -------------------------------------------------------------------------------- 1 | unit Validators.Attributes; 2 | 3 | interface 4 | 5 | uses 6 | Validators.Engine, System.Generics.Collections; 7 | 8 | const 9 | EmailRegex 10 | : string = 11 | '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'; 12 | //'/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'; 13 | 14 | type 15 | 16 | ValidationAttribute = class abstract(TCustomAttribute) 17 | protected 18 | FMessage: string; 19 | FContext: string; 20 | function DoValidate(aValue: string): boolean; virtual; abstract; 21 | public 22 | constructor Create(aContext: string; aMessage: string); 23 | property Context: string read FContext; 24 | function Validate(aValue: string): IValidationResult; 25 | end; 26 | 27 | RequiredValidationAttribute = class(ValidationAttribute) 28 | public 29 | function DoValidate(aValue: string): boolean; override; 30 | end; 31 | 32 | MaxLengthValidationAttribute = class(ValidationAttribute) 33 | protected 34 | FLength: Integer; 35 | public 36 | constructor Create(aContext: string; aMessage: string; aLength: Integer); 37 | function DoValidate(aValue: string): boolean; override; 38 | end; 39 | 40 | MinLengthValidationAttribute = class(MaxLengthValidationAttribute) 41 | public 42 | function DoValidate(aValue: string): boolean; override; 43 | end; 44 | 45 | RegexValidationAttribute = class(ValidationAttribute) 46 | private 47 | FRegex: string; 48 | public 49 | constructor Create(aContext: string; aMessage: string; aRegex: string); 50 | function DoValidate(aValue: string): boolean; override; 51 | end; 52 | 53 | EmailValidationAttribute = class(RegexValidationAttribute) 54 | constructor Create(aContext: string; aMessage: string); 55 | end; 56 | 57 | EntityValidationAttribute = class(ValidationAttribute) 58 | end; 59 | 60 | implementation 61 | 62 | uses 63 | System.SysUtils, System.RegularExpressions; 64 | 65 | { RequiredValidationAttribute } 66 | 67 | function RequiredValidationAttribute.DoValidate(aValue: string): boolean; 68 | begin 69 | Result := not aValue.IsEmpty; 70 | end; 71 | 72 | { MaxLengthValidationAttribute } 73 | 74 | constructor MaxLengthValidationAttribute.Create(aContext: string; 75 | aMessage: string; aLength: Integer); 76 | begin 77 | inherited Create(aContext, aMessage); 78 | FLength := aLength; 79 | end; 80 | 81 | function MaxLengthValidationAttribute.DoValidate(aValue: string): boolean; 82 | begin 83 | Result := Length(aValue) <= FLength; 84 | end; 85 | 86 | { RegexValidationAttribute } 87 | 88 | constructor RegexValidationAttribute.Create(aContext: string; aMessage: string; 89 | aRegex: string); 90 | begin 91 | inherited Create(aContext, aMessage); 92 | FRegex := aRegex; 93 | end; 94 | 95 | function RegexValidationAttribute.DoValidate(aValue: string): boolean; 96 | begin 97 | Result := TRegEx.IsMatch(aValue, FRegex); 98 | end; 99 | 100 | { ValidationAttribute } 101 | 102 | constructor ValidationAttribute.Create(aContext: string; aMessage: string); 103 | begin 104 | inherited Create; 105 | FMessage := aMessage; 106 | FContext := aContext; 107 | end; 108 | 109 | function ValidationAttribute.Validate(aValue: string): IValidationResult; 110 | var 111 | lIsValid: boolean; 112 | begin 113 | Result := TValidationResult.Create; 114 | lIsValid := DoValidate(aValue); 115 | if (not lIsValid) then 116 | Result.AddBrokenRules([FMessage]); 117 | end; 118 | 119 | { MinLengthValidationAttribute } 120 | 121 | function MinLengthValidationAttribute.DoValidate(aValue: string): boolean; 122 | begin 123 | Result := Length(aValue) >= FLength; 124 | end; 125 | 126 | { EmailValidationAttribute } 127 | 128 | constructor EmailValidationAttribute.Create(aContext, aMessage: string); 129 | begin 130 | inherited Create(aContext, aMessage, EmailRegex); 131 | end; 132 | 133 | end. 134 | -------------------------------------------------------------------------------- /source/Validators.Engine.pas: -------------------------------------------------------------------------------- 1 | unit Validators.Engine; 2 | 3 | interface 4 | 5 | uses 6 | System.RTTI, System.JSON, System.Generics.Collections; 7 | 8 | type 9 | 10 | TBrokenRules = array of string; 11 | 12 | TBrokenRulesHelper = record helper for TBrokenRules 13 | private 14 | function asJsonArray: TJSONArray; 15 | end; 16 | 17 | IValidationResult = interface 18 | ['{14B7A1EF-DCD0-416C-BAF1-CF25A6F6E202}'] 19 | function GetBrokenRules: TBrokenRules; 20 | procedure SetBrokenRules(aBrokenRules: TBrokenRules); 21 | procedure AddBrokenRules(aBrokenRules: TBrokenRules); 22 | property BrokenRules: TBrokenRules read GetBrokenRules write SetBrokenRules; 23 | function IsValid(const aRaiseExceptionIfNot: boolean = false): boolean; 24 | end; 25 | 26 | TValidationResult = class(TInterfacedObject, IValidationResult) 27 | protected 28 | FBrokenRules: TBrokenRules; 29 | public 30 | function GetBrokenRules: TBrokenRules; 31 | procedure SetBrokenRules(aBrokenRules: TBrokenRules); 32 | procedure AddBrokenRules(aBrokenRules: TBrokenRules); 33 | property BrokenRules: TBrokenRules read GetBrokenRules write SetBrokenRules; 34 | function IsValid(const aRaiseExceptionIfNot: boolean = false): boolean; 35 | end; 36 | 37 | IValidator = interface 38 | ['{A81A5167-68BB-49D3-B2F8-BC0557FA240C}'] 39 | function Validate(aEntity: T): IValidationResult; 40 | end; 41 | 42 | IValidatable = interface 43 | ['{01643E54-2058-4C42-BD98-462EA78E1CAB}'] 44 | function Validate(aValidator: IValidator; 45 | out aBrokenRules: TBrokenRules): boolean; 46 | end; 47 | 48 | IValidatorContainer = interface 49 | ['{DCC0B831-822B-4159-B132-10587E8BFDFB}'] 50 | procedure RegisterValidatorFor(aType: TClass; aContext: string); 51 | function GetValidatorFor(aType: TClass; aContext: string) 52 | : IValidator; 53 | end; 54 | 55 | TBaseValidatorContainer = class(TObject) 56 | private 57 | FRegistry: TDictionary>; 58 | public 59 | constructor Create; 60 | destructor Destroy; override; 61 | procedure RegisterValidatorFor(aContext: string; 62 | aValidator: IValidator); 63 | function GetValidatorFor(aContext: string): IValidator; 64 | end; 65 | 66 | TValidationEngine = class(TObject) 67 | private 68 | class var FRTTIContext: TRttiContext; 69 | class var FValidationContainer: TBaseValidatorContainer; 70 | public 71 | class constructor Create; 72 | class destructor Destroy; 73 | class function Validate(aObject: T; aContext: string) 74 | : IValidationResult; 75 | class function PropertyValidation(aObject: TObject; aContext: string) 76 | : IValidationResult; 77 | class function EntityValidation(aObject: T; aContext: string) 78 | : IValidationResult; 79 | class property ValidationContainer: TBaseValidatorContainer 80 | read FValidationContainer; 81 | end; 82 | 83 | implementation 84 | 85 | uses 86 | Validators.Attributes, System.SysUtils; 87 | 88 | { TBrokenRulesHelper } 89 | 90 | function TBrokenRulesHelper.asJsonArray: TJSONArray; 91 | var 92 | I: Integer; 93 | begin 94 | Result := TJSONArray.Create; 95 | for I := Low(self) to High(self) do 96 | Result.Add(self[I]); 97 | end; 98 | 99 | { TRunTimeValidator } 100 | 101 | class constructor TValidationEngine.Create; 102 | begin 103 | FRTTIContext := TRttiContext.Create; 104 | FValidationContainer := TBaseValidatorContainer.Create; 105 | end; 106 | 107 | class destructor TValidationEngine.Destroy; 108 | begin 109 | FRTTIContext.Free; 110 | FValidationContainer.Free; 111 | end; 112 | 113 | class function TValidationEngine.EntityValidation(aObject: T; 114 | aContext: string): IValidationResult; 115 | var 116 | a: TCustomAttribute; 117 | lValidator: IValidator; 118 | begin 119 | Result := TValidationResult.Create; 120 | lValidator := FValidationContainer.GetValidatorFor(aContext); 121 | Result.AddBrokenRules(lValidator.Validate(aObject).BrokenRules); 122 | end; 123 | 124 | class function TValidationEngine.PropertyValidation(aObject: TObject; 125 | aContext: string): IValidationResult; 126 | var 127 | rt: TRttiType; 128 | a: TCustomAttribute; 129 | p: TRttiProperty; 130 | m: TRttiMethod; 131 | begin 132 | Result := TValidationResult.Create; 133 | rt := FRTTIContext.GetType(aObject.ClassType); 134 | for p in rt.GetProperties do 135 | for a in p.GetAttributes do 136 | begin 137 | if not(a is ValidationAttribute) then 138 | continue; 139 | if ValidationAttribute(a).Context <> aContext then 140 | continue; 141 | m := FRTTIContext.GetType(a.ClassType).GetMethod('Validate'); 142 | if m = nil then 143 | continue; 144 | Result.AddBrokenRules(m.Invoke(a, [p.GetValue(aObject).AsString]) 145 | .AsType.BrokenRules); 146 | end; 147 | end; 148 | 149 | class function TValidationEngine.Validate(aObject: T; aContext: string) 150 | : IValidationResult; 151 | var 152 | rt: TRttiType; 153 | cx: TRttiContext; 154 | a: TCustomAttribute; 155 | p: TRttiProperty; 156 | m: TRttiMethod; 157 | lValidator: IValidator; 158 | begin 159 | Result := TValidationResult.Create; 160 | Result.AddBrokenRules(EntityValidation(aObject, aContext).BrokenRules); 161 | Result.AddBrokenRules(PropertyValidation(aObject, aContext).BrokenRules); 162 | end; 163 | 164 | { TBaseValidatorContainer } 165 | 166 | constructor TBaseValidatorContainer.Create; 167 | begin 168 | FRegistry := TDictionary < TClass, TDictionary < string, IInterface >>.Create; 169 | end; 170 | 171 | destructor TBaseValidatorContainer.Destroy; 172 | var 173 | lVal: TDictionary; 174 | begin 175 | for lVal in FRegistry.Values do 176 | lVal.Free; 177 | FRegistry.Free; 178 | inherited; 179 | end; 180 | 181 | function TBaseValidatorContainer.GetValidatorFor(aContext: string) 182 | : IValidator; 183 | begin 184 | Result := FRegistry[T][aContext] as IValidator; 185 | end; 186 | 187 | procedure TBaseValidatorContainer.RegisterValidatorFor(aContext: string; 188 | aValidator: IValidator); 189 | var 190 | lDictionary: TDictionary; 191 | begin 192 | if not FRegistry.TryGetValue(T, lDictionary) then 193 | lDictionary := TDictionary.Create(); 194 | lDictionary.AddOrSetValue(aContext, aValidator); 195 | FRegistry.AddOrSetValue(T, lDictionary); 196 | end; 197 | 198 | { TValidationResult } 199 | 200 | procedure TValidationResult.AddBrokenRules(aBrokenRules: TBrokenRules); 201 | begin 202 | FBrokenRules := FBrokenRules + aBrokenRules; 203 | end; 204 | 205 | function TValidationResult.GetBrokenRules: TBrokenRules; 206 | begin 207 | Result := FBrokenRules; 208 | end; 209 | 210 | function TValidationResult.IsValid(const aRaiseExceptionIfNot: boolean) 211 | : boolean; 212 | begin 213 | Result := Length(FBrokenRules) <= 0; 214 | if (not Result) and (aRaiseExceptionIfNot) then 215 | raise Exception.Create(FBrokenRules.asJsonArray.ToJSON); 216 | end; 217 | 218 | procedure TValidationResult.SetBrokenRules(aBrokenRules: TBrokenRules); 219 | begin 220 | FBrokenRules := aBrokenRules; 221 | end; 222 | 223 | end. 224 | -------------------------------------------------------------------------------- /tests/BOU.pas: -------------------------------------------------------------------------------- 1 | unit BOU; 2 | 3 | interface 4 | 5 | uses 6 | DUnitX.TestFramework, Validators.Attributes, Validators.Engine; 7 | 8 | type 9 | 10 | TBaseTests = class(TObject) 11 | public 12 | [Setup] 13 | procedure Setup; 14 | [TearDown] 15 | procedure TearDown; 16 | end; 17 | 18 | TPerson = class 19 | private 20 | FEmail: string; 21 | FLastname: string; 22 | FFirstname: string; 23 | FAddress: string; 24 | FPwd: string; 25 | procedure SetEmail(const Value: string); 26 | procedure SetFirstname(const Value: string); 27 | procedure SetLastname(const Value: string); 28 | procedure SetAddress(const Value: string); 29 | procedure SetPwd(const Value: string); 30 | public 31 | constructor Create(aFirstname, aLastname, aEmail: string; aPwd: string = ''); 32 | [RequiredValidation('TestRequiredValidation', 'Firstname is required')] 33 | [MaxLengthValidation('TestMaxLenthValidation', 'Firstname is too long', 8)] 34 | [MinLengthValidation('TestMinLenthValidation', 'Firstname is too short', 4)] 35 | property Firstname: string read FFirstname write SetFirstname; 36 | [RequiredValidation('TestRequiredValidation', 'Firstname is required')] 37 | property Lastname: string read FLastname write SetLastname; 38 | [RequiredValidation('TestRequiredValidation', 'Firstname is required')] 39 | [EmailValidation('TestRegexEmailValidation', 'Email wrong')] 40 | property Email: string read FEmail write SetEmail; 41 | property Address: string read FAddress write SetAddress; 42 | [RegexValidation('TestRegexPwdValidation', 'Password not valid', 43 | '^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}')] 44 | property Pwd: string read FPwd write SetPwd; 45 | end; 46 | 47 | TPersonLoginValidator = class(TInterfacedObject, IValidator) 48 | public 49 | function Validate(aEntity: TPerson): IValidationResult; 50 | end; 51 | 52 | implementation 53 | 54 | uses 55 | System.SysUtils; 56 | 57 | { TPerson } 58 | 59 | constructor TPerson.Create(aFirstname, aLastname, aEmail, aPwd: string); 60 | begin 61 | inherited Create; 62 | FFirstname := aFirstname; 63 | FLastname := aLastname; 64 | FEmail := aEmail; 65 | FPwd := aPwd; 66 | end; 67 | 68 | procedure TPerson.SetAddress(const Value: string); 69 | begin 70 | FAddress := Value; 71 | end; 72 | 73 | procedure TPerson.SetEmail(const Value: string); 74 | begin 75 | FEmail := Value; 76 | end; 77 | 78 | procedure TPerson.SetFirstname(const Value: string); 79 | begin 80 | FFirstname := Value; 81 | end; 82 | 83 | procedure TPerson.SetLastname(const Value: string); 84 | begin 85 | FLastname := Value; 86 | end; 87 | 88 | procedure TPerson.SetPwd(const Value: string); 89 | begin 90 | FPwd := Value; 91 | end; 92 | 93 | { TPersonLoginValidator } 94 | 95 | function TPersonLoginValidator.Validate(aEntity: TPerson): IValidationResult; 96 | var 97 | lIsValid: boolean; 98 | begin 99 | Result := TValidationResult.Create; 100 | lIsValid := not(aEntity.Firstname.IsEmpty or aEntity.Lastname.IsEmpty or 101 | aEntity.Email.IsEmpty); 102 | if not lIsValid then 103 | Result.BrokenRules := 104 | ['The fields Firstname, Lastname and Email are mandatory ']; 105 | end; 106 | 107 | { TBaseTests } 108 | 109 | procedure TBaseTests.Setup; 110 | begin 111 | end; 112 | 113 | procedure TBaseTests.TearDown; 114 | begin 115 | 116 | end; 117 | 118 | end. 119 | -------------------------------------------------------------------------------- /tests/EntitiesValidatorsUnitTest.dpr: -------------------------------------------------------------------------------- 1 | program EntitiesValidatorsUnitTest; 2 | 3 | {$IFNDEF TESTINSIGHT} 4 | {$APPTYPE CONSOLE} 5 | {$ENDIF}{$STRONGLINKTYPES ON} 6 | 7 | uses 8 | System.SysUtils, 9 | {$IFDEF TESTINSIGHT} 10 | TestInsight.DUnitX, 11 | {$ENDIF } 12 | DUnitX.Loggers.Console, 13 | DUnitX.Loggers.Xml.NUnit, 14 | DUnitX.TestFramework, 15 | Validators.Properties.Tests in 'Validators.Properties.Tests.pas', 16 | BOU in 'BOU.pas', 17 | Validators.Engine in '..\source\Validators.Engine.pas', 18 | Validators.Attributes in '..\source\Validators.Attributes.pas', 19 | Validators.Custom.Tests in 'Validators.Custom.Tests.pas'; 20 | 21 | var 22 | runner: ITestRunner; 23 | results: IRunResults; 24 | logger: ITestLogger; 25 | nunitLogger: ITestLogger; 26 | 27 | begin 28 | ReportMemoryLeaksOnShutdown := true; 29 | {$IFDEF TESTINSIGHT} 30 | TestInsight.DUnitX.RunRegisteredTests; 31 | exit; 32 | {$ENDIF} 33 | try 34 | // Check command line options, will exit if invalid 35 | TDUnitX.CheckCommandLine; 36 | // Create the test runner 37 | runner := TDUnitX.CreateRunner; 38 | // Tell the runner to use RTTI to find Fixtures 39 | runner.UseRTTI := true; 40 | // tell the runner how we will log things 41 | // Log to the console window 42 | logger := TDUnitXConsoleLogger.Create(true); 43 | runner.AddLogger(logger); 44 | // Generate an NUnit compatible XML File 45 | nunitLogger := TDUnitXXMLNUnitFileLogger.Create 46 | (TDUnitX.Options.XMLOutputFile); 47 | runner.AddLogger(nunitLogger); 48 | runner.FailsOnNoAsserts := False; 49 | // When true, Assertions must be made during tests; 50 | 51 | // Run tests 52 | results := runner.Execute; 53 | if not results.AllPassed then 54 | System.ExitCode := EXIT_ERRORS; 55 | 56 | {$IFNDEF CI} 57 | // We don't want this happening when running under CI. 58 | if TDUnitX.Options.ExitBehavior = TDUnitXExitBehavior.Pause then 59 | begin 60 | System.Write('Done.. press key to quit.'); 61 | System.Readln; 62 | end; 63 | {$ENDIF} 64 | except 65 | on E: Exception do 66 | System.Writeln(E.ClassName, ': ', E.Message); 67 | end; 68 | 69 | end. 70 | -------------------------------------------------------------------------------- /tests/EntitiesValidatorsUnitTest.dproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | {C04887E2-D9B1-4F26-8FF2-BB9B299D89A5} 4 | 18.2 5 | EntitiesValidatorsUnitTest.dpr 6 | True 7 | Debug 8 | Win32 9 | 1 10 | Console 11 | None 12 | 13 | 14 | true 15 | 16 | 17 | true 18 | Base 19 | true 20 | 21 | 22 | true 23 | Base 24 | true 25 | 26 | 27 | true 28 | Base 29 | true 30 | 31 | 32 | true 33 | Base 34 | true 35 | 36 | 37 | true 38 | Base 39 | true 40 | 41 | 42 | true 43 | Base 44 | true 45 | 46 | 47 | true 48 | Base 49 | true 50 | 51 | 52 | true 53 | Base 54 | true 55 | 56 | 57 | true 58 | Cfg_1 59 | true 60 | true 61 | 62 | 63 | true 64 | Base 65 | true 66 | 67 | 68 | TESTINSIGHT;$(DCC_Define) 69 | $(BDS)\bin\delphi_PROJECTICNS.icns 70 | CompanyName=;FileDescription=;FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProductName=;ProductVersion=1.0.0.0;Comments= 71 | $(BDS)\bin\delphi_PROJECTICON.ico 72 | EntitiesValidatorsUnitTest 73 | true 74 | System;Xml;Data;Datasnap;Web;Soap;$(DCC_Namespace) 75 | $(DUnitX);..\source;$(DCC_UnitSearchPath) 76 | 1040 77 | .\$(Platform)\$(Config) 78 | .\$(Platform)\$(Config) 79 | false 80 | false 81 | false 82 | false 83 | false 84 | 85 | 86 | android-support-v4.dex.jar;cloud-messaging.dex.jar;fmx.dex.jar;google-analytics-v2.dex.jar;google-play-billing.dex.jar;google-play-licensing.dex.jar;google-play-services.dex.jar 87 | DBXSqliteDriver;RESTComponents;DBXInterBaseDriver;emsclientfiredac;DataSnapFireDAC;tethering;bindcompfmx;FmxTeeUI;FireDACIBDriver;fmx;FireDACDBXDriver;dbexpress;IndyCore;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;soapserver;bindengine;CloudService;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;IndyIPServer;IndySystem;fmxFireDAC;FireDAC;FireDACSqliteDriver;ibmonitor;FMXTee;soaprtl;DbxCommonDriver;ibxpress;xmlrtl;soapmidas;DataSnapNativeClient;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;CustomIPTransport;bindcomp;IndyIPClient;dbxcds;dsnapxml;DataSnapProviderClient;dbrtl;IndyProtocols;$(DCC_UsePackage) 88 | 89 | 90 | DBXSqliteDriver;RESTComponents;DBXInterBaseDriver;emsclientfiredac;DataSnapFireDAC;tethering;bindcompfmx;FmxTeeUI;FireDACIBDriver;fmx;FireDACDBXDriver;dbexpress;IndyCore;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;soapserver;bindengine;CloudService;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;IndyIPServer;IndySystem;fmxFireDAC;FireDAC;FireDACSqliteDriver;ibmonitor;FMXTee;soaprtl;DbxCommonDriver;ibxpress;xmlrtl;soapmidas;DataSnapNativeClient;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;CustomIPTransport;bindcomp;IndyIPClient;dbxcds;dsnapxml;DataSnapProviderClient;dbrtl;IndyProtocols;fmxase;$(DCC_UsePackage) 91 | 92 | 93 | DBXSqliteDriver;RESTComponents;DBXInterBaseDriver;emsclientfiredac;DataSnapFireDAC;tethering;bindcompfmx;FmxTeeUI;FireDACIBDriver;fmx;FireDACDBXDriver;dbexpress;IndyCore;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;soapserver;bindengine;CloudService;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;IndyIPServer;IndySystem;fmxFireDAC;FireDAC;FireDACSqliteDriver;ibmonitor;FMXTee;soaprtl;DbxCommonDriver;ibxpress;xmlrtl;soapmidas;DataSnapNativeClient;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;CustomIPTransport;bindcomp;IndyIPClient;dbxcds;dsnapxml;DataSnapProviderClient;dbrtl;IndyProtocols;fmxase;$(DCC_UsePackage) 94 | 95 | 96 | DBXSqliteDriver;RESTComponents;DBXInterBaseDriver;emsclientfiredac;DataSnapFireDAC;tethering;bindcompfmx;FmxTeeUI;FireDACIBDriver;fmx;FireDACDBXDriver;dbexpress;IndyCore;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;soapserver;bindengine;CloudService;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;IndyIPServer;IndySystem;fmxFireDAC;FireDAC;FireDACSqliteDriver;ibmonitor;FMXTee;soaprtl;DbxCommonDriver;ibxpress;xmlrtl;soapmidas;DataSnapNativeClient;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;CustomIPTransport;bindcomp;IndyIPClient;dbxcds;dsnapxml;DataSnapProviderClient;dbrtl;IndyProtocols;fmxase;$(DCC_UsePackage) 97 | 98 | 99 | DBXSqliteDriver;RESTComponents;DataSnapServerMidas;DBXInterBaseDriver;emsclientfiredac;DataSnapFireDAC;tethering;FireDACMSSQLDriver;bindcompfmx;DBXOracleDriver;inetdb;FmxTeeUI;emsedge;FireDACIBDriver;fmx;fmxdae;FireDACDBXDriver;dbexpress;IndyCore;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;soapserver;bindengine;DBXMySQLDriver;FireDACOracleDriver;CloudService;FireDACMySQLDriver;DBXFirebirdDriver;FireDACCommonODBC;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;IndyIPServer;IndySystem;fmxFireDAC;FireDAC;emshosting;FireDACSqliteDriver;FireDACPgDriver;ibmonitor;FireDACASADriver;FireDACTDataDriver;FMXTee;soaprtl;DbxCommonDriver;ibxpress;DataSnapServer;xmlrtl;soapmidas;DataSnapNativeClient;fmxobj;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;DBXSybaseASADriver;CustomIPTransport;bindcomp;DBXInformixDriver;IndyIPClient;dbxcds;FireDACODBCDriver;DataSnapIndy10ServerTransport;dsnapxml;DataSnapProviderClient;dbrtl;inetdbxpress;FireDACMongoDBDriver;IndyProtocols;fmxase;$(DCC_UsePackage) 100 | 101 | 102 | CompanyName=;FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProductVersion=1.0.0.0;Comments=;ProgramID=com.embarcadero.$(ModuleName);FileDescription=$(ModuleName);ProductName=$(ModuleName) 103 | DBXSqliteDriver;RESTComponents;DataSnapServerMidas;DBXDb2Driver;DBXInterBaseDriver;vclactnband;vclFireDAC;emsclientfiredac;DataSnapFireDAC;svnui;tethering;FireDACADSDriver;DBXMSSQLDriver;DatasnapConnectorsFreePascal;FireDACMSSQLDriver;vcltouch;vcldb;bindcompfmx;svn;Intraweb;DBXOracleDriver;inetdb;FmxTeeUI;emsedge;FireDACIBDriver;fmx;fmxdae;frx24;vclib;FireDACDBXDriver;dbexpress;IndyCore;vclx;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;DataSnapConnectors;VCLRESTComponents;soapserver;vclie;bindengine;DBXMySQLDriver;FireDACOracleDriver;CloudService;FireDACMySQLDriver;DBXFirebirdDriver;FireDACCommonODBC;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;TsiLang_XE101r;vcl;DBXSybaseASEDriver;IndyIPServer;IndySystem;FireDACDb2Driver;dsnapcon;FireDACMSAccDriver;fmxFireDAC;FireDACInfxDriver;vclimg;TeeDB;FireDAC;emshosting;FireDACSqliteDriver;FireDACPgDriver;ibmonitor;FireDACASADriver;DBXOdbcDriver;FireDACTDataDriver;FMXTee;soaprtl;DbxCommonDriver;ibxpress;Tee;DataSnapServer;xmlrtl;soapmidas;DataSnapNativeClient;fmxobj;vclwinx;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;DBXSybaseASADriver;frxTee24;CustomIPTransport;vcldsnap;bindcomp;appanalytics;DBXInformixDriver;IndyIPClient;bindcompvcl;TeeUI;frxe24;dbxcds;VclSmp;adortl;FireDACODBCDriver;DataSnapIndy10ServerTransport;frxDB24;dsnapxml;DataSnapProviderClient;dbrtl;inetdbxpress;FireDACMongoDBDriver;IndyProtocols;fmxase;$(DCC_UsePackage) 104 | 1033 105 | Winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde;$(DCC_Namespace) 106 | 107 | 108 | DBXSqliteDriver;RESTComponents;DataSnapServerMidas;DBXDb2Driver;DBXInterBaseDriver;vclactnband;vclFireDAC;emsclientfiredac;DataSnapFireDAC;tethering;FireDACADSDriver;DBXMSSQLDriver;DatasnapConnectorsFreePascal;FireDACMSSQLDriver;vcltouch;vcldb;bindcompfmx;Intraweb;DBXOracleDriver;inetdb;FmxTeeUI;emsedge;FireDACIBDriver;fmx;fmxdae;vclib;FireDACDBXDriver;dbexpress;IndyCore;vclx;dsnap;DataSnapCommon;emsclient;FireDACCommon;RESTBackendComponents;DataSnapConnectors;VCLRESTComponents;soapserver;vclie;bindengine;DBXMySQLDriver;FireDACOracleDriver;CloudService;FireDACMySQLDriver;DBXFirebirdDriver;FireDACCommonODBC;FireDACCommonDriver;DataSnapClient;inet;bindcompdbx;IndyIPCommon;vcl;DBXSybaseASEDriver;IndyIPServer;IndySystem;FireDACDb2Driver;dsnapcon;FireDACMSAccDriver;fmxFireDAC;FireDACInfxDriver;vclimg;TeeDB;FireDAC;emshosting;FireDACSqliteDriver;FireDACPgDriver;ibmonitor;FireDACASADriver;DBXOdbcDriver;FireDACTDataDriver;FMXTee;soaprtl;DbxCommonDriver;ibxpress;Tee;DataSnapServer;xmlrtl;soapmidas;DataSnapNativeClient;fmxobj;vclwinx;ibxbindings;rtl;FireDACDSDriver;DbxClientDriver;DBXSybaseASADriver;CustomIPTransport;vcldsnap;bindcomp;appanalytics;DBXInformixDriver;IndyIPClient;bindcompvcl;TeeUI;dbxcds;VclSmp;adortl;FireDACODBCDriver;DataSnapIndy10ServerTransport;dsnapxml;DataSnapProviderClient;dbrtl;inetdbxpress;FireDACMongoDBDriver;IndyProtocols;fmxase;$(DCC_UsePackage) 109 | 110 | 111 | DEBUG;$(DCC_Define) 112 | true 113 | false 114 | true 115 | true 116 | true 117 | 118 | 119 | (None) 120 | 1033 121 | false 122 | 123 | 124 | false 125 | RELEASE;$(DCC_Define) 126 | 0 127 | 0 128 | 129 | 130 | 131 | MainSource 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | Cfg_2 140 | Base 141 | 142 | 143 | Base 144 | 145 | 146 | Cfg_1 147 | Base 148 | 149 | 150 | 151 | Delphi.Personality.12 152 | Console 153 | 154 | 155 | 156 | EntitiesValidatorsUnitTest.dpr 157 | 158 | 159 | Microsoft Office 2000 Sample Automation Server Wrapper Components 160 | Microsoft Office XP Sample Automation Server Wrapper Components 161 | 162 | 163 | 164 | 165 | 166 | true 167 | 168 | 169 | 170 | 171 | true 172 | 173 | 174 | 175 | 176 | true 177 | 178 | 179 | 180 | 181 | true 182 | 183 | 184 | 185 | 186 | EntitiesValidatorsUnitTest.exe 187 | true 188 | 189 | 190 | 191 | 192 | 193 | Contents\Resources 194 | 1 195 | 196 | 197 | 198 | 199 | classes 200 | 1 201 | 202 | 203 | 204 | 205 | Contents\MacOS 206 | 0 207 | 208 | 209 | 1 210 | 211 | 212 | 213 | 214 | 1 215 | 216 | 217 | 1 218 | 219 | 220 | 1 221 | 222 | 223 | 224 | 225 | res\drawable-xxhdpi 226 | 1 227 | 228 | 229 | 230 | 231 | library\lib\mips 232 | 1 233 | 234 | 235 | 236 | 237 | 1 238 | 239 | 240 | 1 241 | 242 | 243 | 0 244 | 245 | 246 | 1 247 | 248 | 249 | 1 250 | 251 | 252 | library\lib\armeabi-v7a 253 | 1 254 | 255 | 256 | 1 257 | 258 | 259 | 260 | 261 | 0 262 | 263 | 264 | 1 265 | .framework 266 | 267 | 268 | 269 | 270 | 1 271 | 272 | 273 | 1 274 | 275 | 276 | 277 | 278 | 1 279 | 280 | 281 | 1 282 | 283 | 284 | 1 285 | 286 | 287 | 288 | 289 | 1 290 | 291 | 292 | 1 293 | 294 | 295 | 1 296 | 297 | 298 | 299 | 300 | ..\$(PROJECTNAME).app.dSYM\Contents\Resources\DWARF 301 | 1 302 | 303 | 304 | ..\$(PROJECTNAME).app.dSYM\Contents\Resources\DWARF 305 | 1 306 | 307 | 308 | 309 | 310 | 1 311 | 312 | 313 | 1 314 | 315 | 316 | 1 317 | 318 | 319 | 320 | 321 | 322 | library\lib\armeabi 323 | 1 324 | 325 | 326 | 327 | 328 | 0 329 | 330 | 331 | 1 332 | 333 | 334 | 1 335 | 336 | 337 | 338 | 339 | 1 340 | 341 | 342 | 1 343 | 344 | 345 | 1 346 | 347 | 348 | 349 | 350 | res\drawable-normal 351 | 1 352 | 353 | 354 | 355 | 356 | res\drawable-xhdpi 357 | 1 358 | 359 | 360 | 361 | 362 | res\drawable-large 363 | 1 364 | 365 | 366 | 367 | 368 | 1 369 | 370 | 371 | 1 372 | 373 | 374 | 1 375 | 376 | 377 | 378 | 379 | Assets 380 | 1 381 | 382 | 383 | Assets 384 | 1 385 | 386 | 387 | 388 | 389 | 390 | res\drawable-hdpi 391 | 1 392 | 393 | 394 | 395 | 396 | library\lib\armeabi-v7a 397 | 1 398 | 399 | 400 | 401 | 402 | 403 | 404 | Assets 405 | 1 406 | 407 | 408 | Assets 409 | 1 410 | 411 | 412 | 413 | 414 | 1 415 | 416 | 417 | 1 418 | 419 | 420 | 1 421 | 422 | 423 | 424 | 425 | res\values 426 | 1 427 | 428 | 429 | 430 | 431 | res\drawable-small 432 | 1 433 | 434 | 435 | 436 | 437 | res\drawable 438 | 1 439 | 440 | 441 | 442 | 443 | 1 444 | 445 | 446 | 1 447 | 448 | 449 | 1 450 | 451 | 452 | 453 | 454 | 1 455 | 456 | 457 | 458 | 459 | res\drawable 460 | 1 461 | 462 | 463 | 464 | 465 | 0 466 | 467 | 468 | 0 469 | 470 | 471 | 0 472 | 473 | 474 | 0 475 | 476 | 477 | 0 478 | 479 | 480 | 0 481 | 482 | 483 | 484 | 485 | library\lib\armeabi-v7a 486 | 1 487 | 488 | 489 | 490 | 491 | 0 492 | .bpl 493 | 494 | 495 | 1 496 | .dylib 497 | 498 | 499 | 1 500 | .dylib 501 | 502 | 503 | 1 504 | .dylib 505 | 506 | 507 | 1 508 | .dylib 509 | 510 | 511 | 512 | 513 | res\drawable-mdpi 514 | 1 515 | 516 | 517 | 518 | 519 | res\drawable-xlarge 520 | 1 521 | 522 | 523 | 524 | 525 | res\drawable-ldpi 526 | 1 527 | 528 | 529 | 530 | 531 | 0 532 | .dll;.bpl 533 | 534 | 535 | 1 536 | .dylib 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | False 550 | False 551 | False 552 | False 553 | False 554 | True 555 | False 556 | 557 | 558 | 12 559 | 560 | 561 | 562 | 563 | 564 | -------------------------------------------------------------------------------- /tests/EntitiesValidatorsUnitTest.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bittimeprofessionals/delphi-entities-validators/ba8a90670478898c62596465885b3792a6d108d8/tests/EntitiesValidatorsUnitTest.res -------------------------------------------------------------------------------- /tests/Validators.Custom.Tests.pas: -------------------------------------------------------------------------------- 1 | unit Validators.Custom.Tests; 2 | 3 | interface 4 | 5 | uses 6 | DUnitX.TestFramework, BOU; 7 | 8 | type 9 | 10 | [TestFixture] 11 | TEntityValidationTests = class(TBaseTests) 12 | public 13 | [TestCase('TestPersonLoginValidationOK', '')] 14 | procedure TestPersonLoginValidationOK(); 15 | [TestCase('TestPersonLoginValidationKO', '')] 16 | procedure TestPersonLoginValidationKO(); 17 | end; 18 | 19 | implementation 20 | 21 | uses 22 | Validators.Engine; 23 | 24 | procedure TEntityValidationTests.TestPersonLoginValidationKO; 25 | var 26 | lPerson: TPerson; 27 | lValidationResult: IValidationResult; 28 | begin 29 | lPerson := TPerson.Create('Tony', 'Stark', ''); 30 | try 31 | TValidationEngine.ValidationContainer.RegisterValidatorFor 32 | ('PersonLoginValidation', TPersonLoginValidator.Create); 33 | lValidationResult := TValidationEngine.EntityValidation(lPerson, 34 | 'PersonLoginValidation'); 35 | Assert.IsFalse(lValidationResult.IsValid); 36 | finally 37 | lPerson.Free; 38 | end; 39 | end; 40 | 41 | procedure TEntityValidationTests.TestPersonLoginValidationOK; 42 | var 43 | lPerson: TPerson; 44 | lValidationResult: IValidationResult; 45 | begin 46 | lPerson := TPerson.Create('Tony', 'Stark', 't.stark@marvel.com'); 47 | try 48 | TValidationEngine.ValidationContainer.RegisterValidatorFor 49 | ('PersonLoginValidation', TPersonLoginValidator.Create); 50 | lValidationResult := TValidationEngine.EntityValidation(lPerson, 51 | 'PersonLoginValidation'); 52 | Assert.IsTrue(lValidationResult.IsValid); 53 | finally 54 | lPerson.Free; 55 | end; 56 | end; 57 | 58 | initialization 59 | 60 | TDUnitX.RegisterTestFixture(TEntityValidationTests); 61 | 62 | end. 63 | -------------------------------------------------------------------------------- /tests/Validators.Properties.Tests.pas: -------------------------------------------------------------------------------- 1 | unit Validators.Properties.Tests; 2 | 3 | interface 4 | 5 | uses 6 | DUnitX.TestFramework, Validators.Attributes, Validators.Engine, BOU; 7 | 8 | type 9 | 10 | [TestFixture] 11 | TValidatorsPropertiesTests = class(TBaseTests) 12 | public 13 | [TestCase('TestPropertyRequired', '')] 14 | procedure TestPropertyRequired; 15 | [TestCase('TestMaxLenthValidationOKtony', 'tony')] 16 | [TestCase('TestMaxLenthValidationOKstark', 'stark')] 17 | [TestCase('TestMaxLenthValidationOKironman1', 'ironman1')] 18 | procedure TestMaxLenthValidationOK(aFirstname: string); 19 | [TestCase('TestMaxLenthValidationKOironman11', 'ironman11')] 20 | [TestCase('TestMaxLenthValidationKOironmanrocks', 'ironmanrocks')] 21 | procedure TestMaxLenthValidationKO(aFirstname: string); 22 | [TestCase('TestMinLenthValidationOKtony', 'tony')] 23 | [TestCase('TestMinLenthValidationOKstark', 'stark')] 24 | procedure TestMinLenthValidationOK(aFirstname: string); 25 | [TestCase('TestMinLenthValidationKOtony', 'ton')] 26 | [TestCase('TestMinLenthValidationKOstark', 'st')] 27 | procedure TestMinLenthValidationKO(aFirstname: string); 28 | 29 | [TestCase('TestRegexPwdValidation_Pippolo1!', 'Pippolo1!')] 30 | [TestCase('TestRegexPwdValidation_pippolo1!', 'Pippolo!1')] 31 | procedure TestRegexPwdValidationOk(aPwd: string); 32 | 33 | [TestCase('TestRegexPwdValidation_Pilo1!', 'Pilo1!')] 34 | [TestCase('TestRegexPwdValidation_pippolo', 'pippolo')] 35 | [TestCase('TestRegexPwdValidation_Pippolo1', 'Pippolo1')] 36 | procedure TestRegexPwdValidationKO(aPwd: string); 37 | 38 | [TestCase('TestRegexEmailValidationOKt.stark@marvel.com', 39 | 't.stark@marvel.com') 40 | ] 41 | [TestCase('TestRegexEmailValidationOKt.stark@marvel.it', 42 | 't.stark@marvel.it') 43 | ] 44 | [TestCase('TestRegexEmailValidationOKt.stark@marvel.eu', 45 | 't.stark@marvel.eu')] 46 | procedure TestEmailValidationOk(aEmail: string); 47 | [TestCase('TestRegexEmailValidationKOt.stark', 't.stark')] 48 | [TestCase('TestRegexEmailValidationKOt.stark@marvel.', 't.stark@marvel.')] 49 | [TestCase('TestRegexEmailValidationKOt.stark@marvel', 't.stark@marvel')] 50 | procedure TestEmailValidationKO(aEmail: string); 51 | 52 | end; 53 | 54 | implementation 55 | 56 | procedure TValidatorsPropertiesTests.TestEmailValidationKO(aEmail: string); 57 | var 58 | lPerson: TPerson; 59 | begin 60 | lPerson := TPerson.Create('Tony', 'Stark', aEmail); 61 | try; 62 | Assert.IsFalse(TValidationEngine.PropertyValidation(lPerson, 63 | 'TestRegexEmailValidation').IsValid); 64 | finally 65 | lPerson.Free; 66 | end; 67 | end; 68 | 69 | procedure TValidatorsPropertiesTests.TestEmailValidationOk(aEmail: string); 70 | var 71 | lPerson: TPerson; 72 | begin 73 | lPerson := TPerson.Create('Tony', 'Stark', aEmail); 74 | try 75 | Assert.IsTrue(TValidationEngine.PropertyValidation(lPerson, 76 | 'TestRegexEmailValidation').IsValid); 77 | finally 78 | lPerson.Free; 79 | end; 80 | end; 81 | 82 | procedure TValidatorsPropertiesTests.TestRegexPwdValidationKO(aPwd: string); 83 | var 84 | lPerson: TPerson; 85 | begin 86 | lPerson := TPerson.Create('Tony', 'Stark', '', aPwd); 87 | try 88 | Assert.IsFalse(TValidationEngine.PropertyValidation(lPerson, 89 | 'TestRegexPwdValidation').IsValid); 90 | finally 91 | lPerson.Free; 92 | end; 93 | end; 94 | 95 | procedure TValidatorsPropertiesTests.TestRegexPwdValidationOk(aPwd: string); 96 | var 97 | lPerson: TPerson; 98 | begin 99 | lPerson := TPerson.Create('Tony', 'Stark', '', aPwd); 100 | try 101 | Assert.IsTrue(TValidationEngine.PropertyValidation(lPerson, 102 | 'TestRegexPwdValidation').IsValid); 103 | finally 104 | lPerson.Free; 105 | end; 106 | end; 107 | 108 | procedure TValidatorsPropertiesTests.TestMaxLenthValidationKO 109 | (aFirstname: string); 110 | var 111 | lPerson: TPerson; 112 | lResult: IValidationResult; 113 | begin 114 | lPerson := TPerson.Create(aFirstname, '', ''); 115 | try 116 | lResult := TValidationEngine.PropertyValidation(lPerson, 117 | 'TestMaxLenthValidation'); 118 | Assert.IsFalse(lResult.IsValid); 119 | Assert.AreEqual(1, Length(lResult.BrokenRules)); 120 | finally 121 | lPerson.Free; 122 | end; 123 | end; 124 | 125 | procedure TValidatorsPropertiesTests.TestMaxLenthValidationOK 126 | (aFirstname: string); 127 | var 128 | lPerson: TPerson; 129 | begin 130 | lPerson := TPerson.Create(aFirstname, '', ''); 131 | try 132 | Assert.IsTrue(TValidationEngine.PropertyValidation(lPerson, 133 | 'TestMaxLenthValidation').IsValid); 134 | finally 135 | lPerson.Free; 136 | end; 137 | end; 138 | 139 | procedure TValidatorsPropertiesTests.TestMinLenthValidationKO 140 | (aFirstname: string); 141 | var 142 | lPerson: TPerson; 143 | begin 144 | lPerson := TPerson.Create(aFirstname, '', ''); 145 | try 146 | Assert.IsFalse(TValidationEngine.PropertyValidation(lPerson, 147 | 'TestMinLenthValidation').IsValid); 148 | finally 149 | lPerson.Free; 150 | end; 151 | end; 152 | 153 | procedure TValidatorsPropertiesTests.TestMinLenthValidationOK 154 | (aFirstname: string); 155 | var 156 | lPerson: TPerson; 157 | begin 158 | lPerson := TPerson.Create(aFirstname, '', ''); 159 | try 160 | Assert.IsTrue(TValidationEngine.PropertyValidation(lPerson, 161 | 'TestMinLenthValidation').IsValid); 162 | finally 163 | lPerson.Free; 164 | end; 165 | end; 166 | 167 | procedure TValidatorsPropertiesTests.TestPropertyRequired; 168 | var 169 | lPerson: TPerson; 170 | begin 171 | lPerson := TPerson.Create('Tony', 'Stark', 't.stark@marvel.com'); 172 | try 173 | Assert.IsTrue(TValidationEngine.PropertyValidation(lPerson, 174 | 'TValidatorsRunTimeTests').IsValid); 175 | finally 176 | lPerson.Free; 177 | end; 178 | end; 179 | 180 | initialization 181 | 182 | TDUnitX.RegisterTestFixture(TValidatorsPropertiesTests); 183 | 184 | end. 185 | --------------------------------------------------------------------------------