nfx-serialization 0.3.0
Cross-platform C++ JSON serialization library with extensible trait capabilities
Loading...
Searching...
No Matches
SchemaValidator.h
Go to the documentation of this file.
1/*
2 * MIT License
3 *
4 * Copyright (c) 2025 nfx
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
32
33#pragma once
34
35#include <optional>
36#include <string>
37#include <string_view>
38#include <vector>
39
40#include "Document.h"
41
42namespace nfx::serialization::json
43{
44 //=====================================================================
45 // ValidationError class
46 //=====================================================================
47
54 class ValidationError final
55 {
56 public:
64 {
65 std::string path;
66 std::string message;
67 std::string constraint;
68 std::string expectedValue = {};
69 std::string actualValue = {};
70 };
71
72 public:
73 //----------------------------------------------
74 // Construction
75 //----------------------------------------------
80 explicit ValidationError( const ErrorEntry& entry );
81
90 ValidationError( std::string path,
91 std::string message,
92 std::string constraint,
93 std::string expectedValue = {},
94 std::string actualValue = {} );
95
96 //----------------------------------------------
97 // Destruction
98 //----------------------------------------------
99
103 ~ValidationError() = default;
104
105 //----------------------------------------------
106 // Accessors
107 //----------------------------------------------
108
113 inline const std::string& path() const noexcept { return m_error.path; }
114
119 inline const std::string& message() const noexcept { return m_error.message; }
120
125 inline const std::string& constraint() const noexcept { return m_error.constraint; }
126
131 inline const std::string& expectedValue() const noexcept { return m_error.expectedValue; }
132
137 inline const std::string& actualValue() const noexcept { return m_error.actualValue; }
138
143 std::string toString() const;
144
145 private:
146 ErrorEntry m_error;
147 };
148
149 //=====================================================================
150 // ValidationResult class
151 //=====================================================================
152
159 {
160 public:
161 //----------------------------------------------
162 // Construction
163 //----------------------------------------------
164
168 ValidationResult() = default;
169
174 explicit ValidationResult( std::vector<ValidationError> errors );
175
176 //----------------------------------------------
177 // Destruction
178 //----------------------------------------------
179
183 ~ValidationResult() = default;
184
185 //----------------------------------------------
186 // Status checking
187 //----------------------------------------------
188
193 inline bool isValid() const noexcept { return m_errors.empty(); }
194
199 inline bool hasErrors() const noexcept { return !m_errors.empty(); }
200
205 inline size_t errorCount() const noexcept { return m_errors.size(); }
206
207 //----------------------------------------------
208 // Error access
209 //----------------------------------------------
210
215 inline const std::vector<ValidationError>& errors() const noexcept { return m_errors; }
216
223 const ValidationError& error( size_t index ) const;
224
229 std::string errorSummary() const;
230
231 //----------------------------------------------
232 // Error manipulation
233 //----------------------------------------------
234
240
246
255 void addError( std::string_view path,
256 std::string_view message,
257 std::string_view constraint,
258 std::string_view expectedValue = {},
259 std::string_view actualValue = {} );
260
261 private:
262 std::vector<ValidationError> m_errors;
263 };
264
265 //=====================================================================
266 // SchemaDraft enumeration
267 //=====================================================================
268
283
284 //=====================================================================
285 // SchemaValidator class
286 //=====================================================================
287
295 class SchemaValidator final
296 {
297 public:
298 //----------------------------------------------
299 // Options
300 //----------------------------------------------
301
305 struct Options
306 {
307 bool strictMode = false;
308 size_t maxDepth = 64;
309 };
310
311 //----------------------------------------------
312 // Construction
313 //----------------------------------------------
314
320
325 explicit SchemaValidator( const Document& schema );
326
333
339
344 SchemaValidator( SchemaValidator&& other ) noexcept;
345
346 //----------------------------------------------
347 // Destruction
348 //----------------------------------------------
349
354
355 //----------------------------------------------
356 // Assignment
357 //----------------------------------------------
358
365
372
373 //----------------------------------------------
374 // Schema management
375 //----------------------------------------------
376
382 bool load( const Document& schema );
383
389 bool load( std::string_view schemaJson );
390
395 bool hasSchema() const;
396
400 void clear();
401
407
408 //----------------------------------------------
409 // Validation operations
410 //----------------------------------------------
411
418 ValidationResult validate( const Document& document ) const;
419
428 std::string_view documentPath = "",
429 std::string_view schemaPath = "" ) const;
430
431 //----------------------------------------------
432 // Schema information
433 //----------------------------------------------
434
439 std::string version() const;
440
446
451 std::string draftString() const;
452
457 std::string title() const;
458
463 std::string description() const;
464
469 const Options& options() const noexcept;
470
471 private:
472 //----------------------------------------------
473 // Pimpl
474 //----------------------------------------------
475
476 void* m_impl;
477 };
478} // namespace nfx::serialization::json
Generic document abstraction for JSON serialization.
SchemaDraft
Enumeration of supported JSON Schema draft versions.
@ Draft201909
JSON Schema Draft 2019-09.
@ Draft202012
JSON Schema Draft 2020-12 (current).
@ Unknown
Schema draft version is not recognized or not specified.
Generic JSON document abstraction for serialization.
Definition Document.h:59
Represents a single JSON schema validation error.
const std::string & expectedValue() const noexcept
Get expected value or constraint.
const std::string & path() const noexcept
Get the JSON path where validation failed.
const std::string & message() const noexcept
Get human-readable error message.
std::string toString() const
Get formatted error string.
const std::string & actualValue() const noexcept
Get actual value found in document.
ValidationError(std::string path, std::string message, std::string constraint, std::string expectedValue={}, std::string actualValue={})
Construct validation error.
const std::string & constraint() const noexcept
Get the constraint type that failed.
ValidationError(const ErrorEntry &entry)
Construct validation error from ErrorEntry struct.
Simple error entry structure for convenient ValidationError construction.
std::string expectedValue
Expected value or constraint.
std::string path
JSON path where error occurred.
std::string message
Human-readable error message.
std::string constraint
Schema constraint that failed.
std::string actualValue
Actual value found in document.
Result of JSON schema validation operation.
const std::vector< ValidationError > & errors() const noexcept
Get all validation errors.
bool hasErrors() const noexcept
Check if validation failed.
ValidationResult()=default
Construct successful validation result.
void addError(std::string_view path, std::string_view message, std::string_view constraint, std::string_view expectedValue={}, std::string_view actualValue={})
Add validation error with details.
void addError(const ValidationError &error)
Add validation error to result.
size_t errorCount() const noexcept
Get number of validation errors.
std::string errorSummary() const
Get formatted error summary.
void addError(const ValidationError::ErrorEntry &entry)
Add validation error from ErrorEntry.
ValidationResult(std::vector< ValidationError > errors)
Construct validation result with errors.
const ValidationError & error(size_t index) const
Get validation error by index.
bool isValid() const noexcept
Check if validation was successful.
SchemaDraft draft() const
Get detected JSON Schema draft version.
SchemaValidator(const SchemaValidator &other)
Copy constructor.
bool load(const Document &schema)
Load JSON schema from Document.
std::string description() const
Get schema description.
ValidationResult validate(const Document &document) const
Validate Document against loaded schema.
void clear()
Clear loaded schema.
std::string draftString() const
Get schema draft version as human-readable string.
std::string version() const
Get schema version/draft URI.
bool hasSchema() const
Check if validator has valid schema loaded.
SchemaValidator(SchemaValidator &&other) noexcept
Move constructor.
Document schema() const
Get current schema as Document.
SchemaValidator(const Document &schema)
Construct validator with schema (default options).
SchemaValidator(const Document &schema, const Options &options)
Construct validator with schema.
const Options & options() const noexcept
Get validation options.
SchemaValidator & operator=(SchemaValidator &&other) noexcept
Move assignment operator.
std::string title() const
Get schema title.
ValidationResult validateAtPath(const Document &document, std::string_view documentPath="", std::string_view schemaPath="") const
Validate Document at specific path against schema.
bool load(std::string_view schemaJson)
Load JSON schema from string.
SchemaValidator()
Default constructor - creates empty validator.
SchemaValidator & operator=(const SchemaValidator &other)
Copy assignment operator.
Configuration options for validation.
size_t maxDepth
Maximum recursion depth (0 = unlimited).
bool strictMode
If true, unknown properties cause validation failure.