AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH validation library documentation

Introduction

AnCH validation library defines fields constraints independently of formats, and validates described objects ( anch::Mapping , anch-utils) without serializing them. anch-json checks the constraints when it reads and writes values ; other formats (CSV, XML) and schema generators (JSON Schema, XSD) use the same constraints (see anch-val.todo ).

Installation

CMake target anch::val (built with anch-json, which depends on it). uuid , date-time and date formats are built with ANCH_UUID and ANCH_DATE (anch-uuid and anch-date are optional dependencies):

find_package(Anch REQUIRED)
target_link_libraries(my-app PRIVATE anch::val)

See installation.

Constraints

Constraints are checked at compile time against the value type: minLength on an integer does not compile. null and absent values are not checked ( anch::val::required is a field constraint, checked by formats).

Constraint Field type JSON Schema keyword
anch::val::minLength(n) , anch::val::maxLength(n) string (length in Unicode code points) minLength , maxLength
anch::val::pattern(regex) string (searched, not anchored) pattern
anch::val::format(name) string (registered formats only) format
anch::val::minimum(v) , anch::val::maximum(v) , anch::val::exclusiveMinimum(v) , anch::val::exclusiveMaximum(v) number minimum , maximum , exclusiveMinimum , exclusiveMaximum
anch::val::multipleOf(v) number (exact for integers, relative tolerance for floating point numbers) multipleOf
anch::val::minItems(n) , anch::val::maxItems(n) , anch::val::uniqueItems collection minItems , maxItems , uniqueItems
anch::val::minProperties(n) , anch::val::maxProperties(n) map minProperties , maxProperties
anch::val::allowed({...}) any comparable type enum
anch::val::items(constraints...) collection or map: constraints are checked on every item items , additionalProperties
anch::val::custom<T>(predicate, message) T

Patterns use std::regex (ECMAScript grammar, on bytes: no UTF-8 character classes) by default: anch::val::setPatternCompiler plugs another engine. Formats are checked by validators registered with anch::val::registerFormat ( email , hostname , ipv4 , ipv6 , uri , byte , and uuid , date-time , date with ANCH_UUID / ANCH_DATE are built-in) ; unknown formats are not checked.
Integers bounds are compared without conversion (an uint64_t field accepts minimum(-1) ).

XSD facets

XSD facet Constraint
length , minLength , maxLength anch::val::length(n) , anch::val::minLength(n) , anch::val::maxLength(n) (strings: code points ; length also counts list items)
pattern anch::val::xsdPattern(regex) (matches the whole value)
enumeration anch::val::allowed({...})
minInclusive , maxInclusive , minExclusive , maxExclusive anch::val::minimum(v) , anch::val::maximum(v) , anch::val::exclusiveMinimum(v) , anch::val::exclusiveMaximum(v)
totalDigits , fractionDigits anch::val::totalDigits(n) , anch::val::fractionDigits(n) (numbers and decimal strings)
minOccurs , maxOccurs anch::val::required , anch::val::minItems(n) , anch::val::maxItems(n)

whiteSpace is a normalization, applied by formats. XSD patterns have their own compiler ( setPatternCompiler): the default one translates them to std::regex when the translation keeps their meaning ( ^ and $ are ordinary characters, \d is ASCII digits) and refuses Unicode properties ( \p{..} , \i , \c , \w ) and character class subtractions:

// XSD facets: whole value patterns, exact length, digits of decimals
anch::val::detail::checkConstraints(std::string("75001"), xsd, anch::val::xsdPattern("\\d{5}"), anch::val::length(5));
anch::val::detail::checkConstraints(19.999, xsd, anch::val::totalDigits(4), anch::val::fractionDigits(2));
for(const anch::val::Violation& violation : xsd.violations()) {
std::cout << violation.message << std::endl;
}
// Value 19.999 has 5 digits, more than totalDigits 4
// Value 19.999 has 3 fraction digits, more than fractionDigits 2

A constraint is a value with a check(value, message) function ; its parameters are public, for schema generators:

// A constraint is a value: check(value, message) ; its parameters are public (schema generators)
std::string message;
if(!minLength.check(std::string(""), message)) {
std::cout << message << " (minLength " << minLength.value << ')' << std::endl; // Length 0 is lower than minLength 1
}

Usage with anch-json:

struct Pet {
std::string name;
int32_t age;
std::vector<std::string> tags;
std::map<std::string,int64_t> scores;
std::optional<std::string> color;
};
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("name", &Pet::name, anch::val::required, anch::val::minLength(1), anch::val::maxLength(32))
.registerField("age", &Pet::age, anch::val::minimum(0), anch::val::maximum(50))
.registerField("tags", &Pet::tags, anch::val::maxItems(5), anch::val::uniqueItems,
anch::val::items(anch::val::minLength(1))) // checked on every tag
.registerField("scores", &Pet::scores, anch::val::items(anch::val::multipleOf(5)))
.registerField("color", &Pet::color, anch::val::allowed({"black", "white"})); // checked when not null
}
};
int
main() {
for(const char* json : {R"({"name":"Rex","age":3,"tags":["dog",""]})",
R"({"name":"Rex","age":3,"scores":{"agility":12}})",
R"({"name":"Rex","age":-1})",
R"({"name":"Rex","color":"brown"})"}) {
try {
std::istringstream input(json);
[[maybe_unused]] Pet pet = anch::json::deserialize<Pet>(input);
} catch(const anch::json::MappingError& error) {
std::cout << error.what() << std::endl;
}
}
return 0;
}

Validation

anch::val::validate checks a value without serializing it: constraints of the fields of described objects and of their nested values (objects, collections items, maps values, std::optional and pointers values). It does not stop on the first violation: every violation is returned with its path ( Path: field names, map keys and items indexes, formatted as a JSON Pointer by pointer() ), in fields registration order. Fields registered with a setter only are not checked, and required fields are not checked (an object always has its fields). anch::val::isValid returns true when there is no violation.
Values are validatable when they are scalars ( anch::val::IsScalar : numbers, enumerations, strings, UUID, dates, ... ; it can be specialized for other value types), described objects, or std::optional , pointers, collections and maps of them: a class which is neither described nor a scalar is refused at compile time, as its description is probably not visible (see anch::Mapping ).

struct Pet {
std::string name;
std::vector<std::string> tags;
};
// Description shared by formats (anch-utils): constraints are anch-val ones
template<>
struct anch::Mapping<Pet> {
static void
registerObject(anch::ObjectMapper<Pet> auto& mapper) {
mapper
.registerField("name", &Pet::name, anch::val::required, anch::val::minLength(1))
.registerField("tags", &Pet::tags, anch::val::items(anch::val::minLength(1)));
}
};
// Every violation of a described object, without serialization
const std::vector<Pet> pets{{"Rex", {"dog"}}, {"", {"cat", ""}}};
for(const anch::val::Violation& violation : anch::val::validate(pets)) {
std::cout << violation.path << ": " << violation.message << std::endl;
}
// /1/name: Length 0 is lower than minLength 1
// /1/tags/1: Length 0 is lower than minLength 1

Contexts

Constraints are checked in a context ( anch::val::CheckContext ): it enables or disables checks and reports violations. anch::val::ValidationContext collects every violation with its path:

// Validation context: every violation is collected with its path (JSON Pointer)
const std::vector<std::string> tags{"dog", "", "brown"};
anch::val::detail::checkConstraints(tags, validation, anch::val::maxItems(2), anch::val::items(anch::val::minLength(1)));
for(const anch::val::Violation& violation : validation.violations()) {
std::cout << '\'' << violation.path << "': " << violation.message << std::endl;
}
// '': Item count 3 is greater than maxItems 2
// '/1': Length 0 is lower than minLength 1

A format specializes anch::val::CheckContext for its contexts (anch-json: reader and writer contexts, which raise anch::json::MappingError ):

// Context of a format which checks constraints while it reads values: the first violation raises its error
struct ReadContext {
std::string path;
};
template<>
struct anch::val::CheckContext<ReadContext> {
static bool
enabled(const ReadContext&) {
return true; // format option
}
static void
violation(ReadContext& context, const std::string& message) {
throw std::invalid_argument(context.path + ": " + message);
}
template<typename F>
static void
item(ReadContext& context, std::string_view key, F&& check) {
const std::size_t size = context.path.size();
context.path += "/" + std::string(key);
check();
context.path.resize(size);
}
template<typename F>
static void
item(ReadContext& context, std::size_t index, F&& check) {
const std::size_t size = context.path.size();
context.path += "/" + std::to_string(index);
check();
context.path.resize(size);
}
};
ReadContext context;
try {
anch::val::detail::checkConstraints(tags, context, anch::val::items(anch::val::minLength(1)));
} catch(const std::invalid_argument& error) {
std::cout << error.what() << std::endl; // /1: Length 0 is lower than minLength 1
}