Skip to content
Download

Defining Validation Rules

Validation rules are defined inside a model’s validate() method.

Select a field with field() and chain the rules that should apply to it:

struct RegisterRequest {
std::string username;
std::string email;
int age;
void validate(mach::ValidationBuilder<RegisterRequest>& validation) const {
validation.field(&RegisterRequest::username)
.minLength(3)
.maxLength(30);
validation.field(&RegisterRequest::email).email();
validation.field(&RegisterRequest::age).min(18);
}
};

Each call to field() selects a member of the model. The rules chained after it apply to that field.

A field can have more than one constraint:

validation.field(&RegisterRequest::username)
.minLength(3)
.maxLength(30)
.notEquals("admin");

The same rule can also be applied multiple times when each call defines a different constraint:

validation.field(&RegisterRequest::username)
.notEquals("admin")
.notEquals("root");

Applying the same parameterless rule more than once has no additional effect:

validation.field(&RegisterRequest::email)
.email()
.email();

In this case, the email rule is applied only once.

This keeps related validation requirements together and makes the model’s constraints easy to read.

For fields with a single rule, keeping the expression on one line is usually clearer:

validation.field(&RegisterRequest::email).email();
validation.field(&RegisterRequest::age).min(18);

Mach includes validation rules for common requirements such as string lengths and formats, numeric values and ranges, regular expressions, and equality checks.

For the complete list of rules and their parameters, see the FieldValidationBuilder API reference.


Next, you’ll learn what happens when validation fails and how Mach returns validation errors.