├── .editorconfig
├── .gitattributes
├── .github
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.yml
│ ├── config.yml
│ └── feature_request.yml
├── README.md
└── workflows
│ ├── ci.yml
│ └── lock.yml
├── .gitignore
├── Build.cmd
├── FluentValidation.AspNetCore.sln
├── License.txt
├── after.FluentValidation.AspNetCore.sln.targets
├── build.ps1
├── build.sh
├── global.json
├── logo
└── fluent-validation-icon.png
├── nuget.config
└── src
├── FluentValidation-Release.snk
├── FluentValidation.AspNetCore
├── Adapters
│ ├── ClientValidatorBase.cs
│ ├── CreditCardClientValidator.cs
│ ├── EmailClientValidator.cs
│ ├── EqualToClientValidator.cs
│ ├── MaxLengthClientValidator.cs
│ ├── MinLengthClientValidator.cs
│ ├── RangeClientValidator.cs
│ ├── RangeMaxClientValidator.cs
│ ├── RangeMinClientValidator.cs
│ ├── RegexClientValidator.cs
│ ├── RequiredClientValidator.cs
│ └── StringLengthClientValidator.cs
├── AssemblyInfo.cs
├── CustomizeValidatorAttribute.cs
├── FluentValidation.AspNetCore.csproj
├── FluentValidation.AspNetCore.csproj.DotSettings
├── FluentValidationBindingMetadataProvider.cs
├── FluentValidationClientModelValidatorProvider.cs
├── FluentValidationModelValidatorProvider.cs
├── FluentValidationMvcConfiguration.cs
├── FluentValidationMvcExtensions.cs
├── FluentValidationObjectModelValidator.cs
├── FluentValidationVisitor.cs
├── IValidatorInterceptor.cs
├── MvcValidationHelper.cs
├── README.md
├── RuleSetForClientSideMessagesAttribute.cs
├── ValidationResultExtensions.cs
└── ValidatorDescriptorCache.cs
└── FluentValidation.Tests.AspNetCore
├── ClientsideMessageTester.cs
├── Controllers
├── ApiTestController.cs
├── ClientsideController.cs
├── HomeController.cs
└── TestController.cs
├── CultureScope.cs
├── DependencyInjectionTests.cs
├── DisableAutoValidationTests.cs
├── DisableDataAnnotationsTests.cs
├── ExtensionTests.cs
├── FluentValidation.Tests.AspNetCore.csproj
├── FluentValidationModelValidatorFilterIntegrationTests.cs
├── GlobalInterceptorTests.cs
├── HttpClientExtensions.cs
├── ImplicitRootCollectionTests.cs
├── ImplicitValidationTests.cs
├── MvcIntegrationTests.cs
├── Pages
├── RulesetTest.cshtml
├── Rulesets
│ ├── DefaultAndSpecifiedRuleSet.cshtml
│ ├── DefaultRuleSet.cshtml
│ ├── MultipleRuleSets.cshtml
│ ├── RuleSetForHandlers.cshtml
│ └── SpecifiedRuleSet.cshtml
├── TestPage1.cshtml
├── TestPageWithPrefix.cshtml
└── _ViewImports.cshtml
├── RazorPagesTests.cs
├── ServiceCollectionExtensionTests.cs
├── ServiceProviderTests.cs
├── Startup.cs
├── TestExtensions.cs
├── TestMessages.Designer.cs
├── TestMessages.resx
├── TestModels.cs
├── TestModels_ClientSIde.cs
├── TestPageModel.cs
├── TypeFilterTests.cs
├── Views
├── Clientside
│ ├── Inputs.cshtml
│ ├── RuleSet.cshtml
│ └── _TestPartial.cshtml
└── _ViewImports.cshtml
├── WebAppFixture.cs
└── xunit.runner.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # top-most EditorConfig file
2 | root = true
3 |
4 | [*]
5 | indent_style = space
6 | indent_size = 2
7 | trim_trailing_whitespace=true
8 | insert_final_newline=true
9 |
10 | # Microsoft .NET properties
11 | csharp_new_line_before_members_in_object_initializers=false
12 | csharp_new_line_before_open_brace=none
13 | csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion
14 | csharp_style_var_elsewhere=true:hint
15 | csharp_style_var_for_built_in_types=true:hint
16 | csharp_style_var_when_type_is_apparent=true:hint
17 | dotnet_style_predefined_type_for_locals_parameters_members=true:hint
18 | dotnet_style_predefined_type_for_member_access=true:hint
19 | dotnet_style_qualification_for_event=false:warning
20 | dotnet_style_qualification_for_field=false:warning
21 | dotnet_style_qualification_for_method=false:warning
22 | dotnet_style_qualification_for_property=false:warning
23 | dotnet_style_require_accessibility_modifiers=for_non_interface_members:hint
24 |
25 | # ReSharper properties
26 | resharper_add_imports_to_deepest_scope=true
27 | resharper_autodetect_indent_settings=true
28 | resharper_braces_redundant=false
29 | resharper_csharp_indent_style=tab
30 | resharper_csharp_wrap_lines=false
31 | resharper_place_accessorholder_attribute_on_same_line=False
32 | resharper_use_indent_from_vs=false
33 | resharper_xmldoc_indent_child_elements=RemoveIndent
34 | resharper_xmldoc_indent_text=RemoveIndent
35 | resharper_xmldoc_wrap_lines=false
36 |
37 | [*.cs]
38 | indent_style = tab
39 | tab_width = 2
40 | indent_size = tab
41 | end_of_line = crlf
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.doc diff=astextplain
2 | *.DOC diff=astextplain
3 | *.docx diff=astextplain
4 | *.DOCX diff=astextplain
5 | *.dot diff=astextplain
6 | *.DOT diff=astextplain
7 | *.pdf diff=astextplain
8 | *.PDF diff=astextplain
9 | *.rtf diff=astextplain
10 | *.RTF diff=astextplain
11 |
12 | *.jpg binary
13 | *.png binary
14 | *.gif binary
15 |
16 | *.cs -text diff=csharp
17 | *.vb -text
18 | *.c -text
19 | *.cpp -text
20 | *.cxx -text
21 | *.h -text
22 | *.hxx -text
23 | *.py -text
24 | *.rb -text
25 | *.java -text
26 | *.html -text
27 | *.htm -text
28 | *.css -text
29 | *.scss -text
30 | *.sass -text
31 | *.less -text
32 | *.js -text
33 | *.lisp -text
34 | *.clj -text
35 | *.sql -text
36 | *.php -text
37 | *.lua -text
38 | *.m -text
39 | *.asm -text
40 | *.erl -text
41 | *.fs -text
42 | *.fsx -text
43 | *.hs -text
44 |
45 | *.csproj -text merge=union
46 | *.vbproj -text merge=union
47 | *.fsproj -text merge=union
48 | *.dbproj -text merge=union
49 | *.sln -text merge=union
50 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | FluentValidation has adopted the code of conduct defined by the Contributor Covenant, which can be found on the [.NET Foundation website](http://www.dotnetfoundation.org/code-of-conduct).
4 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## General support, feedback, and discussions
2 | FluentValidation is maintained on a voluntary basis, and unfortunately this means we are unable to provide general support or answer questions on usage due to the time and effort required to moderate these. The issue tracker should only be used for bug reports in the core FluentValidation library, or feature requests where appropriate. Requests for general support or questions on usage will be closed. We appreciate that this may appear strict, but is necessary to protect the free time and mental health of the project's maintainers. Thank you for understanding.
3 |
4 | ## Supporting the project
5 | If you use FluentValidation in a commercial project, please sponsor the project financially. FluentValidation is developed and supported by [@JeremySkinner](https://github.com/JeremySkinner) for free in his spare time and financial sponsorship helps keep the project going. You can sponsor the project via either [GitHub sponsors](https://github.com/sponsors/JeremySkinner) or [OpenCollective](https://opencollective.com/FluentValidation).
6 |
7 |
8 | ## Filing bug reports and feature requests
9 | The best way to get your bug fixed is to be as detailed as you can be about the problem.
10 |
11 | Please check both the documentation at https://fluentvalidation.net and old issues first to see if your question has already been answered.
12 |
13 | If not, then please provide the exact version of FluentValidation that you're using along with a detailed explanation of the issue and complete steps to reproduce the problem. Issues that don't provide enough information to reproduce will be closed.
14 |
15 | Please ensure all sample code is properly formatted and readable (GitHub supports [markdown](https://github.github.com/github-flavored-markdown/)). Issues that don't include all necessary code (or a sample project) to reproduce will be closed.
16 |
17 | We do our best to respond to all bug reports and feature requests, but FluentValidation is maintained on a voluntary basis and we cannot guarantee how quickly these will be looked at.
18 |
19 | ## Contributing Code
20 | Please open an issue to discuss new feature requests before submitting a Pull Request. This allows the maintainers to discuss whether your feature is a suitable fit for the project before any code is written. Please don't open a pull request without first discussing whether the feature fits with the project roadmap.
21 |
22 | ## Building the code
23 | Run `Build.cmd` (windows) or build.sh (Linux/mac) from the command line. This builds the project and runs tests. Building requires the following software to be installed:
24 |
25 | * Windows Powershell or Powershell Core
26 | * .NET Core 3.1 SDK
27 | * .NET Core 2.1 SDK
28 | * .NET 5 SDK
29 |
30 | ## Contributing code and content
31 | You will need to sign a [Contributor License Agreement](https://cla.dotnetfoundation.org/) before submitting your pull request.
32 |
33 | Make sure you can build the code. Familiarize yourself with the project workflow and our coding conventions. If you don't know what a pull request is read this article: https://help.github.com/articles/using-pull-requests.
34 |
35 | If you wish to submit a new feature, please open an issue to discuss it with the project maintainers - don't open a pull request without first discussing whether the feature fits with the project roadmap.
36 |
37 | Tests must be provided for all pull requests that add or change functionality.
38 |
39 | Please ensure that you follow the existing code-style when adding new code to the project. This may seem pedantic, but it makes it much easier to review pull requests when contributed code matches the existing project style. Specifically:
40 | - Please ensure that your editor is configured to use tabs for indentation, not spaces
41 | - Please ensure that the project copyright notice is included in the header for all files.
42 | - Please ensure `using` statements are inside the namespace declaration
43 | - Please ensure that all opening braces are on the end of line:
44 |
45 | ```csharp
46 | // Opening braces should be on the end of the line like this
47 | if (foo) {
48 |
49 | }
50 |
51 | // Not like this:
52 | if (foo)
53 | {
54 |
55 | }
56 | ```
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [JeremySkinner]
4 | open_collective: FluentValidation
5 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: "\U0001F41B Bug Report"
2 | description: "Report a reproducible bug in FluentValidation. Also use this template if you're having trouble upgrading from version 10.x
3 | to 11.x"
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | Thanks for taking the time to file a bug report! Before filling out a new issue, please first check to see if your question has been answered in an existing issue, [in the readme](https://github.com/FluentValidation/FluentValidation.AspNetCore#aspnet-core-integration-for-fluentvalidation) or in the documentation for the main FluentValidation project at [https://docs.fluentvalidation.net](https://docs.fluentvalidation.net)
9 |
10 | **Please note** FluentValidation is supported for free on a voluntary basis. If you use FluentValidation please [sponsor the project](https://github.com/sponsors/JeremySkinner) so that its development can continue. Bug reports from sponsors will be prioritised.
11 |
12 | Please take the time to fill in this form as completely as possible. If you leave out sections there is a high likelihood your issue will be closed.
13 | - type: input
14 | attributes:
15 | label: FluentValidation.AspNetCore version
16 | description: Which version of FluentValidation.AspNetCore are you using?
17 | validations:
18 | required: true
19 | - type: input
20 | attributes:
21 | label: FluentValidation version
22 | description: Which version of FluentValidation are you using?
23 | validations:
24 | required: true
25 | - type: dropdown
26 | attributes:
27 | label: ASP.NET version
28 | description: Please select which version of ASP.NET Core you're running
29 | options:
30 | - .NET 7 (Preview)
31 | - .NET 6
32 | - .NET 5
33 | - .NET Core 3.1
34 | - An older version
35 | validations:
36 | required: true
37 | - type: textarea
38 | attributes:
39 | label: Summary
40 | description: A clear and concise description of the issue that you're having.
41 | validations:
42 | required: true
43 | - type: textarea
44 | attributes:
45 | label: Steps to Reproduce
46 | description: "Please include all the steps necessary to reproduce the issue, including any sample code (preferably in the form of a runnable unit test). Alternatively, please provide a link to a *minimal* sample project. Please do not include screenshots of code."
47 | validations:
48 | required: true
49 | - type: markdown
50 | attributes:
51 | value: |
52 | Please ensure that any code samples are readable and [properly formatted as code blocks](https://docs.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks).
53 |
54 | **Please realise that it is up to you to debug your code thoroughly. Be as certain as possible that the bug is with FluentValidation, and not with your own code, prior to opening an issue.**
55 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: General Support and Usage questions
4 | url: "https://github.com/FluentValidation/FluentValidation.AspNetCore/blob/main/.github/CONTRIBUTING.md"
5 | about: We are unable to provide general support for usage of the library
6 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: "\U0001F64B Feature Request"
2 | description: 'Want us to add something to FluentValidation?'
3 | body:
4 | - type: markdown
5 | attributes:
6 | value: |
7 | Thanks for helping us make FluentValidation even better! Please fill out this form as thoroughly as possible.
8 |
9 | **Please note** FluentValidation is supported for free on a voluntary basis. If you use FluentValidation please [sponsor the project](https://github.com/sponsors/JeremySkinner) so that its development can continue. Feature requests from sponsors will be prioritised.
10 | - type: textarea
11 | attributes:
12 | label: Is your feature request related to a problem? Please describe.
13 | description: A clear and concise description of what the problem is.
14 | validations:
15 | required: false
16 | - type: textarea
17 | attributes:
18 | label: Describe the solution you'd like
19 | description: A clear and concise description of what you want to happen.
20 | validations:
21 | required: true
22 | - type: textarea
23 | attributes:
24 | label: Describe alternatives you've considered
25 | description: A clear and concise description of any alternative solutions or features you've considered.
26 | - type: textarea
27 | attributes:
28 | label: Additional Context
29 | description: Add any other context or sample code about the feature request here.
30 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | build:
13 | strategy:
14 | matrix:
15 | os: ['windows-latest', 'ubuntu-latest']
16 | runs-on: ${{ matrix.os }}
17 | steps:
18 | - name: Checkout
19 | uses: actions/checkout@v2
20 | with:
21 | fetch-depth: 0
22 |
23 | - name: Setup dotnet
24 | uses: actions/setup-dotnet@v2
25 | with:
26 | dotnet-version: |
27 | 9.0.x
28 | 7.0.100
29 | 6.0.x
30 |
31 | - name: Build and Test
32 | run: ./build.ps1
33 | shell: pwsh
34 | env:
35 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
36 |
--------------------------------------------------------------------------------
/.github/workflows/lock.yml:
--------------------------------------------------------------------------------
1 | name: 'Lock closed issues'
2 |
3 | on:
4 | schedule:
5 | - cron: '0 0 * * *'
6 |
7 | permissions:
8 | contents: read
9 |
10 | jobs:
11 | lock:
12 | permissions:
13 | issues: write # for dessant/lock-threads to lock issues
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: dessant/lock-threads@v2
17 | with:
18 | github-token: ${{ github.token }}
19 | process-only: 'issues'
20 | issue-lock-inactive-days: '14'
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | *.suo
3 | *.user
4 | bin
5 | Bin
6 | obj
7 | _ReSharper*
8 | *.csproj.user
9 | *.resharper.user
10 | *.suo
11 | *.cache
12 | TestResult.xml
13 | *.orig
14 | .hg/
15 | .hgignore
16 | packages/
17 | *.sln.ide/
18 | artifacts/
19 | TestResults/
20 | .vs/
21 | *.lock.json
22 | *.ncrunch*
23 | .idea/
24 | .build/
25 | docs/_site/
26 | docs/Gemfile.lock
27 | docs/_build/
28 | src/FluentValidation.Tests.Benchmarks/BenchmarkDotNet.Artifacts/
29 |
--------------------------------------------------------------------------------
/Build.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | powershell -noprofile -ExecutionPolicy Unrestricted -File build.ps1 %*
--------------------------------------------------------------------------------
/FluentValidation.AspNetCore.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27130.2036
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3906F280-A567-4AD7-A0EF-7253E95E7852}"
7 | ProjectSection(SolutionItems) = preProject
8 | .editorconfig = .editorconfig
9 | EndProjectSection
10 | EndProject
11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FluentValidation.AspNetCore", "src\FluentValidation.AspNetCore\FluentValidation.AspNetCore.csproj", "{D8A44C11-51B8-4AA1-9391-C4F89078181C}"
12 | EndProject
13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentValidation.Tests.AspNetCore", "src\FluentValidation.Tests.AspNetCore\FluentValidation.Tests.AspNetCore.csproj", "{3DFE3035-9685-4B76-AF21-074BCD8F69B7}"
14 | EndProject
15 | Global
16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
17 | Debug|Any CPU = Debug|Any CPU
18 | Release|Any CPU = Release|Any CPU
19 | EndGlobalSection
20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
21 | {D8A44C11-51B8-4AA1-9391-C4F89078181C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22 | {D8A44C11-51B8-4AA1-9391-C4F89078181C}.Debug|Any CPU.Build.0 = Debug|Any CPU
23 | {D8A44C11-51B8-4AA1-9391-C4F89078181C}.Release|Any CPU.ActiveCfg = Release|Any CPU
24 | {D8A44C11-51B8-4AA1-9391-C4F89078181C}.Release|Any CPU.Build.0 = Release|Any CPU
25 | {3DFE3035-9685-4B76-AF21-074BCD8F69B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {3DFE3035-9685-4B76-AF21-074BCD8F69B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {3DFE3035-9685-4B76-AF21-074BCD8F69B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {3DFE3035-9685-4B76-AF21-074BCD8F69B7}.Release|Any CPU.Build.0 = Release|Any CPU
29 | EndGlobalSection
30 | GlobalSection(SolutionProperties) = preSolution
31 | HideSolutionNode = FALSE
32 | EndGlobalSection
33 | GlobalSection(ExtensibilityGlobals) = postSolution
34 | SolutionGuid = {33CD33AF-2F26-44A0-BA94-F9299272362B}
35 | EndGlobalSection
36 | EndGlobal
37 |
--------------------------------------------------------------------------------
/License.txt:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/after.FluentValidation.AspNetCore.sln.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Release
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/build.ps1:
--------------------------------------------------------------------------------
1 | param(
2 | [string]$configuration = 'Release',
3 | [string]$path = $PSScriptRoot,
4 | [string[]]$targets = 'default'
5 | )
6 |
7 | $ErrorActionPreference = "Stop"
8 |
9 | # Boostrap posh-build
10 | $build_dir = Join-Path $path ".build"
11 | if (! (Test-Path (Join-Path $build_dir "Posh-Build.ps1"))) {
12 | Write-Host "Installing posh-build..."; New-Item -Type Directory $build_dir -ErrorAction Ignore | Out-Null;
13 | (New-Object Net.WebClient).DownloadFile('https://raw.githubusercontent.com/jeremyskinner/posh-build/master/Posh-Build.ps1', "$build_dir/Posh-Build.ps1")
14 | }
15 | . (Join-Path $build_dir "Posh-Build.ps1")
16 |
17 | # Set these variables as desired
18 | $packages_dir = Join-Path $build_dir "packages"
19 | $output_dir = Join-Path $build_dir $configuration
20 | $solution_file = Join-Path $path "FluentValidation.AspNetCore.sln"
21 |
22 | target default -depends compile, test, deploy
23 |
24 | target compile {
25 | Invoke-Dotnet build $solution_file -c $configuration --no-incremental
26 | }
27 |
28 | target test {
29 | Invoke-Dotnet test $solution_file -c $configuration --no-build --logger trx
30 | }
31 |
32 | target deploy {
33 | Remove-Item $packages_dir -Force -Recurse -ErrorAction Ignore 2> $null
34 | Remove-Item $output_dir -Force -Recurse -ErrorAction Ignore 2> $null
35 |
36 | Invoke-Dotnet pack $solution_file -c $configuration
37 | }
38 |
39 | target publish {
40 | $key = $Env:NUGET_API_KEY
41 | Nuget-Push -directory $packages_dir -key $key -prompt $true
42 | }
43 |
44 | Start-Build $targets
45 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | pwsh -noprofile ./build.ps1 $@
2 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.100",
4 | "rollForward": "latestFeature"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/logo/fluent-validation-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FluentValidation/FluentValidation.AspNetCore/e891499e1e83dcc1310076ff10dc8a2bcc739563/logo/fluent-validation-icon.png
--------------------------------------------------------------------------------
/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/src/FluentValidation-Release.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FluentValidation/FluentValidation.AspNetCore/e891499e1e83dcc1310076ff10dc8a2bcc739563/src/FluentValidation-Release.snk
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/ClientValidatorBase.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using System.ComponentModel;
23 | using Internal;
24 | using Validators;
25 | using System.Linq;
26 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
27 |
28 | public abstract class ClientValidatorBase : IClientModelValidator {
29 | public IPropertyValidator Validator { get; }
30 | public IValidationRule Rule { get; }
31 | public IRuleComponent Component { get; }
32 |
33 | public ClientValidatorBase(IValidationRule rule, IRuleComponent component) {
34 | Component = component;
35 | Validator = component.Validator;
36 | Rule = rule;
37 | }
38 |
39 | public abstract void AddValidation(ClientModelValidationContext context);
40 |
41 | protected static bool MergeAttribute(IDictionary attributes, string key, string value) {
42 | if (attributes.ContainsKey(key)) {
43 | return false;
44 | }
45 |
46 | attributes.Add(key, value);
47 | return true;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/CreditCardClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using Internal;
23 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
24 | using Resources;
25 | using Validators;
26 |
27 | internal class CreditCardClientValidator : ClientValidatorBase {
28 | public CreditCardClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
29 | }
30 |
31 | public override void AddValidation(ClientModelValidationContext context) {
32 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
33 | var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
34 | string message;
35 | try {
36 | message = Component.GetUnformattedErrorMessage();
37 | }
38 | catch (NullReferenceException) {
39 | message = cfg.LanguageManager.GetString("CreditCardValidator");
40 | }
41 | message = formatter.BuildMessage(message);
42 | MergeAttribute(context.Attributes, "data-val", "true");
43 | MergeAttribute(context.Attributes, "data-val-creditcard", message);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/EmailClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using Internal;
23 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
24 | using Resources;
25 | using Validators;
26 |
27 | internal class EmailClientValidator : ClientValidatorBase {
28 |
29 | public EmailClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
30 | }
31 |
32 | public override void AddValidation(ClientModelValidationContext context) {
33 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
34 | var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
35 |
36 | string messageTemplate;
37 | try {
38 | messageTemplate = Component.GetUnformattedErrorMessage();
39 | }
40 | catch (NullReferenceException) {
41 | messageTemplate = cfg.LanguageManager.GetString("EmailValidator");
42 | }
43 |
44 | string message = formatter.BuildMessage(messageTemplate);
45 | MergeAttribute(context.Attributes, "data-val", "true");
46 | MergeAttribute(context.Attributes, "data-val-email", message);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/EqualToClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using System.Reflection;
23 | using Internal;
24 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
25 | using Resources;
26 | using Validators;
27 |
28 | internal class EqualToClientValidator : ClientValidatorBase {
29 | IComparisonValidator EqualValidator => (IComparisonValidator)Validator;
30 |
31 | public EqualToClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
32 | }
33 |
34 | public override void AddValidation(ClientModelValidationContext context) {
35 |
36 | var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;
37 |
38 | if (propertyToCompare != null) {
39 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
40 | // If propertyToCompare is not null then we're comparing to another property.
41 | // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
42 | // We only care about property comparisons in this case.
43 |
44 | var comparisonDisplayName =
45 | cfg.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
46 | ?? propertyToCompare.Name.SplitPascalCase();
47 |
48 | var formatter = cfg.MessageFormatterFactory()
49 | .AppendPropertyName(Rule.GetDisplayName(null))
50 | .AppendArgument("ComparisonValue", comparisonDisplayName);
51 |
52 | string messageTemplate;
53 | try {
54 | messageTemplate = Component.GetUnformattedErrorMessage();
55 | }
56 | catch (NullReferenceException) {
57 | messageTemplate = cfg.LanguageManager.GetString("EqualValidator");
58 | }
59 | string message = formatter.BuildMessage(messageTemplate);
60 | MergeAttribute(context.Attributes, "data-val", "true");
61 | MergeAttribute(context.Attributes, "data-val-equalto", message);
62 | MergeAttribute(context.Attributes, "data-val-equalto-other", "*." + propertyToCompare.Name);
63 | }
64 |
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/MaxLengthClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright (c) .NET Foundation and contributors.
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 | //
17 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
18 |
19 | #endregion
20 |
21 | namespace FluentValidation.AspNetCore;
22 |
23 | using System;
24 | using Internal;
25 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
26 | using Resources;
27 | using Validators;
28 |
29 | internal class MaxLengthClientValidator : ClientValidatorBase {
30 | public override void AddValidation(ClientModelValidationContext context) {
31 | var lengthVal = (ILengthValidator) Validator;
32 |
33 | MergeAttribute(context.Attributes, "data-val", "true");
34 | MergeAttribute(context.Attributes, "data-val-maxlength", GetErrorMessage(lengthVal, context));
35 | MergeAttribute(context.Attributes, "data-val-maxlength-max", lengthVal.Max.ToString());
36 | }
37 |
38 | private string GetErrorMessage(ILengthValidator lengthVal, ClientModelValidationContext context) {
39 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
40 |
41 | var formatter = cfg.MessageFormatterFactory()
42 | .AppendPropertyName(Rule.GetDisplayName(null))
43 | .AppendArgument("MinLength", lengthVal.Min)
44 | .AppendArgument("MaxLength", lengthVal.Max);
45 |
46 | string message;
47 | try {
48 | message = Component.GetUnformattedErrorMessage();
49 | }
50 | catch (NullReferenceException) {
51 | message = cfg.LanguageManager.GetString("MaximumLength_Simple");
52 | }
53 |
54 | if (message.Contains("{TotalLength}")) {
55 | message = cfg.LanguageManager.GetString("MaximumLength_Simple");
56 | }
57 |
58 | message = formatter.BuildMessage(message);
59 | return message;
60 | }
61 |
62 | public MaxLengthClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/MinLengthClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright (c) .NET Foundation and contributors.
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 | //
17 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
18 |
19 | #endregion
20 |
21 | namespace FluentValidation.AspNetCore;
22 |
23 | using System;
24 | using Internal;
25 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
26 | using Resources;
27 | using Validators;
28 |
29 | internal class MinLengthClientValidator : ClientValidatorBase {
30 | public override void AddValidation(ClientModelValidationContext context) {
31 | var lengthVal = (ILengthValidator) Validator;
32 |
33 | MergeAttribute(context.Attributes, "data-val", "true");
34 | MergeAttribute(context.Attributes, "data-val-minlength", GetErrorMessage(lengthVal, context));
35 | MergeAttribute(context.Attributes, "data-val-minlength-min", lengthVal.Min.ToString());
36 | }
37 |
38 | private string GetErrorMessage(ILengthValidator lengthVal, ClientModelValidationContext context) {
39 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
40 |
41 | var formatter = cfg.MessageFormatterFactory()
42 | .AppendPropertyName(Rule.GetDisplayName(null))
43 | .AppendArgument("MinLength", lengthVal.Min)
44 | .AppendArgument("MaxLength", lengthVal.Max);
45 |
46 | string message;
47 | try {
48 | message = Component.GetUnformattedErrorMessage();
49 | }
50 | catch (NullReferenceException) {
51 | message = cfg.LanguageManager.GetString("MinimumLength_Simple");
52 | }
53 |
54 | if (message.Contains("{TotalLength}")) {
55 | message = cfg.LanguageManager.GetString("MinimumLength_Simple");
56 | }
57 |
58 | message = formatter.BuildMessage(message);
59 | return message;
60 | }
61 |
62 | public MinLengthClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/RangeClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using Internal;
21 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
22 | using Resources;
23 | using System;
24 | using System.Globalization;
25 | using Validators;
26 |
27 | internal class RangeClientValidator : ClientValidatorBase {
28 | IBetweenValidator RangeValidator => (IBetweenValidator)Validator;
29 |
30 | public RangeClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
31 |
32 | }
33 |
34 | public override void AddValidation(ClientModelValidationContext context) {
35 | if (RangeValidator.To != null && RangeValidator.From != null) {
36 | MergeAttribute(context.Attributes, "data-val", "true");
37 | MergeAttribute(context.Attributes, "data-val-range", GetErrorMessage(context));
38 | MergeAttribute(context.Attributes, "data-val-range-max", Convert.ToString(RangeValidator.To, CultureInfo.InvariantCulture));
39 | MergeAttribute(context.Attributes, "data-val-range-min", Convert.ToString(RangeValidator.From, CultureInfo.InvariantCulture));
40 | }
41 | }
42 |
43 | private string GetErrorMessage(ClientModelValidationContext context) {
44 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
45 |
46 | var formatter = cfg.MessageFormatterFactory()
47 | .AppendPropertyName(Rule.GetDisplayName(null))
48 | .AppendArgument("From", RangeValidator.From)
49 | .AppendArgument("To", RangeValidator.To);
50 |
51 | string message;
52 |
53 | try {
54 | message = Component.GetUnformattedErrorMessage();
55 | }
56 | catch (NullReferenceException) {
57 | message = cfg.LanguageManager.GetString("InclusiveBetween_Simple");
58 | }
59 |
60 | if (message.Contains("{PropertyValue}")) {
61 | message = cfg.LanguageManager.GetString("InclusiveBetween_Simple");
62 | }
63 | message = formatter.BuildMessage(message);
64 |
65 | return message;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/RangeMaxClientValidator.cs:
--------------------------------------------------------------------------------
1 | namespace FluentValidation.AspNetCore;
2 |
3 | using Internal;
4 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
5 | using Resources;
6 | using System;
7 | using System.Globalization;
8 | using Validators;
9 |
10 | internal class RangeMaxClientValidator : ClientValidatorBase {
11 | IComparisonValidator RangeValidator => (IComparisonValidator)Validator;
12 |
13 | public RangeMaxClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
14 | }
15 |
16 | public override void AddValidation(ClientModelValidationContext context) {
17 | var compareValue = RangeValidator.ValueToCompare;
18 |
19 | if (compareValue != null) {
20 | MergeAttribute(context.Attributes, "data-val", "true");
21 | MergeAttribute(context.Attributes, "data-val-range", GetErrorMessage(context));
22 | MergeAttribute(context.Attributes, "data-val-range-max", Convert.ToString(compareValue, CultureInfo.InvariantCulture));
23 | MergeAttribute(context.Attributes, "data-val-range-min", "0");
24 | }
25 | }
26 |
27 | private string GetErrorMessage(ClientModelValidationContext context) {
28 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
29 |
30 | var formatter = cfg.MessageFormatterFactory()
31 | .AppendPropertyName(Rule.GetDisplayName(null))
32 | .AppendArgument("ComparisonValue", RangeValidator.ValueToCompare);
33 |
34 | string message;
35 |
36 | try {
37 | message = Component.GetUnformattedErrorMessage();
38 | }
39 | catch (NullReferenceException) {
40 | message = cfg.LanguageManager.GetString("LessThanOrEqualValidator");
41 | }
42 |
43 | message = formatter.BuildMessage(message);
44 |
45 | return message;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/RangeMinClientValidator.cs:
--------------------------------------------------------------------------------
1 | namespace FluentValidation.AspNetCore;
2 |
3 | using Internal;
4 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
5 | using Resources;
6 | using System;
7 | using System.Globalization;
8 | using Validators;
9 |
10 | internal class RangeMinClientValidator : ClientValidatorBase {
11 | IComparisonValidator RangeValidator => (IComparisonValidator)Validator;
12 |
13 | public RangeMinClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
14 |
15 | }
16 |
17 | public override void AddValidation(ClientModelValidationContext context) {
18 | var compareValue = RangeValidator.ValueToCompare;
19 |
20 | if (compareValue != null) {
21 | MergeAttribute(context.Attributes, "data-val", "true");
22 | MergeAttribute(context.Attributes, "data-val-range", GetErrorMessage(context));
23 | MergeAttribute(context.Attributes, "data-val-range-min", Convert.ToString(compareValue, CultureInfo.InvariantCulture));
24 | }
25 | }
26 |
27 | private string GetErrorMessage(ClientModelValidationContext context) {
28 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
29 |
30 | var formatter = cfg.MessageFormatterFactory()
31 | .AppendPropertyName(Rule.GetDisplayName(null))
32 | .AppendArgument("ComparisonValue", RangeValidator.ValueToCompare);
33 |
34 | string message;
35 |
36 | try {
37 | message = Component.GetUnformattedErrorMessage();
38 | }
39 | catch (NullReferenceException) {
40 | message = cfg.LanguageManager.GetString("GreaterThanOrEqualValidator");
41 | }
42 |
43 | message = formatter.BuildMessage(message);
44 |
45 | return message;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/RegexClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using Internal;
23 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
24 | using Resources;
25 | using Validators;
26 |
27 | internal class RegexClientValidator : ClientValidatorBase {
28 |
29 | public RegexClientValidator(IValidationRule rule, IRuleComponent component)
30 | : base(rule, component) {
31 | }
32 |
33 | public override void AddValidation(ClientModelValidationContext context) {
34 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
35 | var regexVal = (IRegularExpressionValidator)Validator;
36 | var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
37 | string messageTemplate;
38 | try {
39 | messageTemplate = Component.GetUnformattedErrorMessage();
40 | }
41 | catch (NullReferenceException) {
42 | messageTemplate = cfg.LanguageManager.GetString("RegularExpressionValidator");
43 | }
44 |
45 | string message = formatter.BuildMessage(messageTemplate);
46 |
47 | MergeAttribute(context.Attributes, "data-val", "true");
48 | MergeAttribute(context.Attributes, "data-val-regex", message);
49 | MergeAttribute(context.Attributes, "data-val-regex-pattern", regexVal.Expression);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/RequiredClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using Internal;
23 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
24 | using Resources;
25 | using Validators;
26 |
27 | internal class RequiredClientValidator : ClientValidatorBase{
28 | public RequiredClientValidator(IValidationRule rule, IRuleComponent component) : base(rule, component) {
29 |
30 | }
31 |
32 | public override void AddValidation(ClientModelValidationContext context) {
33 | MergeAttribute(context.Attributes, "data-val", "true");
34 | MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context));
35 | }
36 |
37 | private string GetErrorMessage(ClientModelValidationContext context) {
38 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
39 | var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
40 | string messageTemplate;
41 | try {
42 | messageTemplate = Component.GetUnformattedErrorMessage();
43 | }
44 | catch (NullReferenceException) {
45 | messageTemplate = cfg.LanguageManager.GetString("NotEmptyValidator");
46 | }
47 |
48 | var message = formatter.BuildMessage(messageTemplate);
49 | return message;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/Adapters/StringLengthClientValidator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using Internal;
22 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
23 | using Validators;
24 |
25 | internal class StringLengthClientValidator : ClientValidatorBase {
26 | public StringLengthClientValidator(IValidationRule rule, IRuleComponent component)
27 | : base(rule, component) {
28 | }
29 |
30 | public override void AddValidation(ClientModelValidationContext context) {
31 | var lengthVal = (ILengthValidator)Validator;
32 |
33 | MergeAttribute(context.Attributes, "data-val", "true");
34 | MergeAttribute(context.Attributes, "data-val-length", GetErrorMessage(lengthVal, context));
35 | MergeAttribute(context.Attributes, "data-val-length-max", lengthVal.Max.ToString());
36 | MergeAttribute(context.Attributes, "data-val-length-min", lengthVal.Min.ToString());
37 | }
38 |
39 | private string GetErrorMessage(ILengthValidator lengthVal, ClientModelValidationContext context) {
40 | var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
41 |
42 | var formatter = cfg.MessageFormatterFactory()
43 | .AppendPropertyName(Rule.GetDisplayName(null))
44 | .AppendArgument("MinLength", lengthVal.Min)
45 | .AppendArgument("MaxLength", lengthVal.Max);
46 |
47 | string message;
48 | try {
49 | message = Component.GetUnformattedErrorMessage();
50 | }
51 | catch (NullReferenceException) {
52 | if (lengthVal is IExactLengthValidator) {
53 | message = cfg.LanguageManager.GetString("ExactLength_Simple");
54 | }
55 | else {
56 | message = cfg.LanguageManager.GetString("Length_Simple");
57 | }
58 | }
59 |
60 |
61 | if (message.Contains("{TotalLength}")) {
62 | if (lengthVal is IExactLengthValidator) {
63 | message = cfg.LanguageManager.GetString("ExactLength_Simple");
64 | }
65 | else {
66 | message = cfg.LanguageManager.GetString("Length_Simple");
67 | }
68 | }
69 |
70 | message = formatter.BuildMessage(message);
71 | return message;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 |
4 | [assembly : AssemblyVersion("11.0.0.0")]
5 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/CustomizeValidatorAttribute.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 |
19 | namespace FluentValidation.AspNetCore;
20 |
21 | using System;
22 | using FluentValidation.Internal;
23 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
24 | using Microsoft.Extensions.DependencyInjection;
25 | using System.Linq;
26 |
27 | [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
28 | public class CustomizeValidatorAttribute : Attribute {
29 |
30 | ///
31 | /// Specifies the ruleset which should be used when executing this validator.
32 | /// This can be a comma separated list of rulesets. The string "*" can be used to indicate all rulesets.
33 | /// The string "default" can be used to specify those rules not in an explict ruleset.
34 | ///
35 | public string RuleSet { get; set; }
36 |
37 | ///
38 | /// Specifies a whitelist of properties that should be validated, as a comma-separated list.
39 | ///
40 | public string Properties { get; set; }
41 |
42 | ///
43 | /// Specifies an interceptor that can be used to customize the validation process.
44 | ///
45 | public Type Interceptor { get; set; }
46 |
47 | ///
48 | /// Indicates whether this model should skip being validated. The default is false.
49 | ///
50 | public bool Skip { get; set; }
51 |
52 | ///
53 | /// Builds a validator selector from the options specified in the attribute's properties.
54 | ///
55 | ///
56 | public IValidatorSelector ToValidatorSelector(ModelValidationContext mvContext) {
57 | IValidatorSelector selector;
58 |
59 | if (!string.IsNullOrEmpty(RuleSet)) {
60 | var rulesets = RuleSet.Split(',', ';')
61 | .Select(x => x.Trim())
62 | .ToArray();
63 | selector = CreateRulesetValidatorSelector(mvContext, rulesets);
64 | }
65 | else if (!string.IsNullOrEmpty(Properties)) {
66 | var properties = Properties.Split(',', ';')
67 | .Select(x => x.Trim())
68 | .ToArray();
69 | selector = CreateMemberNameValidatorSelector(mvContext, properties);
70 | }
71 | else {
72 | selector = CreateDefaultValidatorSelector(mvContext);
73 | }
74 |
75 | return selector;
76 | }
77 |
78 | protected virtual IValidatorSelector CreateRulesetValidatorSelector(ModelValidationContext mvContext, string[] ruleSets) {
79 | var cfg = mvContext.ActionContext.HttpContext.RequestServices.GetRequiredService();
80 | return cfg.ValidatorSelectors.RulesetValidatorSelectorFactory(ruleSets);
81 | }
82 |
83 | protected virtual IValidatorSelector CreateMemberNameValidatorSelector(ModelValidationContext mvContext, string[] properties) {
84 | var cfg = mvContext.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
85 | return cfg.ValidatorSelectors.MemberNameValidatorSelectorFactory(properties);
86 | }
87 |
88 | protected virtual IValidatorSelector CreateDefaultValidatorSelector(ModelValidationContext mvContext) {
89 | var cfg = mvContext.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
90 | return cfg.ValidatorSelectors.DefaultValidatorSelectorFactory();
91 | }
92 |
93 | public IValidatorInterceptor GetInterceptor() {
94 | if (Interceptor == null) return null;
95 |
96 | if (!typeof(IValidatorInterceptor).IsAssignableFrom(Interceptor)) {
97 | throw new InvalidOperationException("Type {0} is not an IValidatorInterceptor. The Interceptor property of CustomizeValidatorAttribute must implement IValidatorInterceptor.");
98 | }
99 |
100 | var instance = Activator.CreateInstance(Interceptor) as IValidatorInterceptor;
101 |
102 | if (instance == null) {
103 | throw new InvalidOperationException("Type {0} is not an IValidatorInterceptor. The Interceptor property of CustomizeValidatorAttribute must implement IValidatorInterceptor.");
104 | }
105 |
106 | return instance;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/FluentValidation.AspNetCore.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netcoreapp3.1;net5.0;net6.0
4 | 11.3.1
5 | FluentValidation.AspNetCore
6 | FluentValidation.AspNetCore
7 | FluentValidation.AspNetCore
8 | AspNetCore integration for FluentValidation
9 |
10 | FluentValidation 11 is a major release. Please read the upgrade guide at https://docs.fluentvalidation.net/en/latest/upgrading-to-11.html
11 |
12 | Full release notes can be found at https://github.com/FluentValidation/FluentValidation.AspNetCore/releases
13 |
14 | True
15 | False
16 | bin\$(Configuration)\$(TargetFramework)\FluentValidation.AspNetCore.xml
17 | embedded
18 | README.md
19 | Jeremy Skinner
20 | 10
21 | $(NoWarn);1701;1702;1591
22 | true
23 | https://fluentvalidation.net
24 | Copyright (c) Jeremy Skinner, .NET Foundation, and contributors 2008-2022
25 | https://github.com/FluentValidation/FluentValidation.AspNetCore
26 | fluent-validation-icon.png
27 | Apache-2.0
28 | false
29 | en
30 | $(MSBuildProjectDirectory)/../FluentValidation-Release.snk
31 | $(MSBuildProjectDirectory)/../../.build/packages
32 | true
33 | true
34 | true
35 | true
36 | 11.0.0
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/FluentValidation.AspNetCore.csproj.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | True
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/FluentValidationBindingMetadataProvider.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 |
19 | namespace FluentValidation.AspNetCore;
20 |
21 | using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
22 |
23 | internal class FluentValidationBindingMetadataProvider : IBindingMetadataProvider {
24 | public const string Prefix = "_FV_REQUIRED|";
25 |
26 | ///
27 | /// If we're validating a non-nullable value type then
28 | /// MVC will automatically add a "Required" error message.
29 | /// We prefix these messages with a placeholder, so we can identify and remove them
30 | /// during the validation process.
31 | ///
32 | ///
33 | ///
34 | ///
35 | ///
36 | public void CreateBindingMetadata(BindingMetadataProviderContext context) {
37 | if (context.Key.MetadataKind == ModelMetadataKind.Property) {
38 | var original = context.BindingMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor;
39 | context.BindingMetadata.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(s => Prefix + original(s));
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/FluentValidationClientModelValidatorProvider.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright (c) .NET Foundation and contributors.
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | //
16 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
17 | #endregion
18 | namespace FluentValidation.AspNetCore;
19 |
20 | using System;
21 | using System.Collections.Generic;
22 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
23 | using System.Linq;
24 | using FluentValidation.Internal;
25 | using FluentValidation.Validators;
26 | using Microsoft.AspNetCore.Http;
27 | using Microsoft.AspNetCore.Mvc.DataAnnotations;
28 |
29 | public delegate IClientModelValidator FluentValidationClientValidatorFactory(ClientValidatorProviderContext context, IValidationRule rule, IRuleComponent component);
30 |
31 | ///
32 | /// Used to generate clientside metadata from FluentValidation's rules.
33 | ///
34 | public class FluentValidationClientModelValidatorProvider : IClientModelValidatorProvider{
35 | private readonly IHttpContextAccessor _httpContextAccessor;
36 | private readonly ValidatorDescriptorCache _descriptorCache = new();
37 |
38 | public Dictionary ClientValidatorFactories { get; } = new() {
39 | { typeof(INotNullValidator), (context, rule, component) => new RequiredClientValidator(rule, component) },
40 | { typeof(INotEmptyValidator), (context, rule, component) => new RequiredClientValidator(rule, component) },
41 | { typeof(IEmailValidator), (context, rule, component) => new EmailClientValidator(rule, component) },
42 | { typeof(IRegularExpressionValidator), (context, rule, component) => new RegexClientValidator(rule, component) },
43 | { typeof(IMaximumLengthValidator), (context, rule, component) => new MaxLengthClientValidator(rule, component) },
44 | { typeof(IMinimumLengthValidator), (context, rule, component) => new MinLengthClientValidator(rule, component) },
45 | { typeof(IExactLengthValidator), (context, rule, component) => new StringLengthClientValidator(rule, component)},
46 | { typeof(ILengthValidator), (context, rule, component) => new StringLengthClientValidator(rule, component)},
47 | { typeof(IInclusiveBetweenValidator), (context, rule, component) => new RangeClientValidator(rule, component) },
48 | { typeof(IGreaterThanOrEqualValidator), (context, rule, component) => new RangeMinClientValidator(rule, component) },
49 | { typeof(ILessThanOrEqualValidator), (context, rule, component) => new RangeMaxClientValidator(rule, component) },
50 | { typeof(IEqualValidator), (context, rule, component) => new EqualToClientValidator(rule, component) },
51 | { typeof(ICreditCardValidator), (context, rule, component) => new CreditCardClientValidator(rule, component) },
52 | };
53 |
54 | public FluentValidationClientModelValidatorProvider(IHttpContextAccessor httpContextAccessor) {
55 | _httpContextAccessor = httpContextAccessor;
56 | }
57 |
58 | public void Add(Type validatorType, FluentValidationClientValidatorFactory factory) {
59 | if (validatorType == null) throw new ArgumentNullException(nameof(validatorType));
60 | if (factory == null) throw new ArgumentNullException(nameof(factory));
61 |
62 | ClientValidatorFactories[validatorType] = factory;
63 | }
64 |
65 | public void CreateValidators(ClientValidatorProviderContext context) {
66 | var descriptor = _descriptorCache.GetCachedDescriptor(context, _httpContextAccessor);
67 |
68 | if (descriptor != null) {
69 | var propertyName = context.ModelMetadata.PropertyName;
70 |
71 | var validatorsWithRules = from rule in descriptor.GetRulesForMember(propertyName)
72 | where !rule.HasCondition && !rule.HasAsyncCondition
73 | let components = rule.Components
74 | where components.Any()
75 | from component in components
76 | where !component.HasCondition && !component.HasAsyncCondition
77 | let modelValidatorForProperty = GetModelValidator(context, rule, component)
78 | where modelValidatorForProperty != null
79 | select modelValidatorForProperty;
80 |
81 | var list = validatorsWithRules.ToList();
82 |
83 | foreach (var propVal in list) {
84 | context.Results.Add(new ClientValidatorItem {
85 | Validator = propVal,
86 | IsReusable = false
87 | });
88 | }
89 |
90 | // Must ensure there is at least 1 ClientValidatorItem, set to IsReusable = false
91 | // otherwise MVC will cache the list of validators, assuming there will always be 0 validators for that property
92 | // Which isn't true - we may be using the RulesetForClientsideMessages attribute (or some other mechanism) that can change the client validators that are available
93 | // depending on some context.
94 | if (list.Count == 0) {
95 | context.Results.Add(new ClientValidatorItem {IsReusable = false});
96 | }
97 |
98 | HandleNonNullableValueTypeRequiredRule(context);
99 | }
100 | }
101 |
102 | // If the property is a non-nullable value type, then MVC will have already generated a Required rule.
103 | // If we've provided our own Required rule, then remove the MVC one.
104 | protected virtual void HandleNonNullableValueTypeRequiredRule(ClientValidatorProviderContext context) {
105 | bool isNonNullableValueType = !TypeAllowsNullValue(context.ModelMetadata.ModelType);
106 |
107 | if (isNonNullableValueType) {
108 | bool fvHasRequiredRule = context.Results.Any(x => x.Validator is RequiredClientValidator);
109 |
110 | if (fvHasRequiredRule) {
111 | var dataAnnotationsRequiredRule = context.Results
112 | .FirstOrDefault(x => x.Validator is RequiredAttributeAdapter);
113 | context.Results.Remove(dataAnnotationsRequiredRule);
114 | }
115 | }
116 | }
117 |
118 | protected virtual IClientModelValidator GetModelValidator(ClientValidatorProviderContext context, IValidationRule rule, IRuleComponent component) {
119 | var type = component.Validator.GetType();
120 |
121 | var factory = ClientValidatorFactories
122 | .Where(x => x.Key.IsAssignableFrom(type))
123 | .Select(x => x.Value)
124 | .FirstOrDefault();
125 |
126 | if (factory != null) {
127 | bool shouldExecute;
128 | var ruleSetToGenerateClientSideRules = RuleSetForClientSideMessagesAttribute.GetRuleSetsForClientValidation(_httpContextAccessor?.HttpContext);
129 |
130 | if (ruleSetToGenerateClientSideRules.Contains(RulesetValidatorSelector.WildcardRuleSetName)) {
131 | // If RuleSet "*" is specified, include all rules.
132 | shouldExecute = true;
133 | }
134 | else {
135 | bool executeDefaultRule = ruleSetToGenerateClientSideRules.Contains(RulesetValidatorSelector.DefaultRuleSetName, StringComparer.OrdinalIgnoreCase)
136 | && (rule.RuleSets == null || rule.RuleSets.Length == 0 || rule.RuleSets.Contains(RulesetValidatorSelector.DefaultRuleSetName, StringComparer.OrdinalIgnoreCase));
137 |
138 | shouldExecute = (rule.RuleSets != null && ruleSetToGenerateClientSideRules.Intersect(rule.RuleSets, StringComparer.OrdinalIgnoreCase).Any()) || executeDefaultRule;
139 | }
140 |
141 | if (shouldExecute) {
142 | return factory.Invoke(context, rule, component);
143 | }
144 | }
145 |
146 | return null;
147 | }
148 |
149 | private bool TypeAllowsNullValue(Type type) {
150 | return (!type.IsValueType || Nullable.GetUnderlyingType(type) != null);
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/src/FluentValidation.AspNetCore/FluentValidationModelValidatorProvider.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright (c) .NET Foundation and contributors.
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 | //
17 | // The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
18 |
19 | #endregion
20 |
21 | namespace FluentValidation.AspNetCore;
22 |
23 | using System;
24 | using System.Collections.Generic;
25 | using System.Linq;
26 | using Internal;
27 | using Microsoft.AspNetCore.Mvc;
28 | using Microsoft.AspNetCore.Mvc.ModelBinding;
29 | using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
30 | using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
31 | using Microsoft.Extensions.DependencyInjection;
32 | using Results;
33 |
34 | ///
35 | /// ModelValidatorProvider implementation only used for child properties.
36 | ///
37 | public class FluentValidationModelValidatorProvider : IModelValidatorProvider {
38 | private readonly bool _implicitValidationEnabled;
39 | private readonly bool _implicitRootCollectionElementValidationEnabled;
40 | private readonly Func _filter;
41 |
42 | public FluentValidationModelValidatorProvider(bool implicitValidationEnabled)
43 | : this(implicitValidationEnabled, false, default) {
44 | }
45 |
46 | public FluentValidationModelValidatorProvider(
47 | bool implicitValidationEnabled,
48 | bool implicitRootCollectionElementValidationEnabled)
49 | : this(implicitValidationEnabled, implicitRootCollectionElementValidationEnabled, default) {
50 | }
51 |
52 | public FluentValidationModelValidatorProvider(
53 | bool implicitValidationEnabled,
54 | bool implicitRootCollectionElementValidationEnabled,
55 | Func filter) {
56 | _implicitValidationEnabled = implicitValidationEnabled;
57 | _implicitRootCollectionElementValidationEnabled = implicitRootCollectionElementValidationEnabled;
58 | _filter = filter;
59 | }
60 |
61 | public virtual void CreateValidators(ModelValidatorProviderContext context) {
62 | context.Results.Add(new ValidatorItem {
63 | IsReusable = false,
64 | Validator = new FluentValidationModelValidator(_implicitValidationEnabled, _implicitRootCollectionElementValidationEnabled, _filter),
65 | });
66 | }
67 | }
68 |
69 | ///
70 | /// FluentValidation's implementation of an ASP.NET Core model validator.
71 | ///
72 | public class FluentValidationModelValidator : IModelValidator {
73 | private readonly bool _implicitValidationEnabled;
74 | private readonly bool _implicitRootCollectionElementValidationEnabled;
75 | private readonly Func _filter;
76 |
77 | public FluentValidationModelValidator(bool implicitValidationEnabled)
78 | : this(implicitValidationEnabled, false, default) {
79 | }
80 |
81 | public FluentValidationModelValidator(
82 | bool implicitValidationEnabled,
83 | bool implicitRootCollectionElementValidationEnabled)
84 | : this(implicitValidationEnabled, implicitRootCollectionElementValidationEnabled, default) {
85 | }
86 |
87 | public FluentValidationModelValidator(
88 | bool implicitValidationEnabled,
89 | bool implicitRootCollectionElementValidationEnabled,
90 | Func filter) {
91 | _implicitValidationEnabled = implicitValidationEnabled;
92 | _implicitRootCollectionElementValidationEnabled = implicitRootCollectionElementValidationEnabled;
93 | _filter = filter;
94 | }
95 |
96 | public virtual IEnumerable Validate(ModelValidationContext mvContext) {
97 | if (ShouldSkip(mvContext)) {
98 | return Enumerable.Empty();
99 | }
100 |
101 | IValidator validator;
102 |
103 | #pragma warning disable CS0618
104 | var factory = mvContext.ActionContext.HttpContext.RequestServices.GetService();
105 | #pragma warning restore CS0618
106 |
107 | if (factory != null) {
108 | validator = factory?.GetValidator(mvContext.ModelMetadata.ModelType);
109 | }
110 | else {
111 | validator = mvContext.ActionContext.HttpContext.RequestServices.GetService(mvContext.ModelMetadata.ModelType) as IValidator;
112 | }
113 |
114 |
115 | if (validator != null) {
116 | var customizations = GetCustomizations(mvContext.ActionContext, mvContext.Model);
117 |
118 | if (customizations.Skip) {
119 | return Enumerable.Empty();
120 | }
121 |
122 | if (mvContext.Container != null) {
123 | var containerCustomizations = GetCustomizations(mvContext.ActionContext, mvContext.Container);
124 | if (containerCustomizations.Skip) {
125 | return Enumerable.Empty();
126 | }
127 | }
128 |
129 | var selector = customizations.ToValidatorSelector(mvContext);
130 | var interceptor = customizations.GetInterceptor()
131 | ?? validator as IValidatorInterceptor
132 | ?? mvContext.ActionContext.HttpContext.RequestServices.GetService();
133 |
134 | IValidationContext context = new ValidationContext