Validify
A procedural macro that provides attributes for field validation and modifiers. Particularly useful in the context of web payloads.
Modifiers
| Modifier | Type | Description |
|---|---|---|
| trim* | String | Removes surrounding whitespace |
| uppercase* | String | Calls .to_uppercase() |
| lowercase* | String | Calls .to_lowercase() |
| capitalize* | String | Makes the first char of the string uppercase |
| custom | Any | Takes a function whose argument is &mut <Type> |
| validify* | impl Validify / impl Iterator<Item = impl Validify> | Can only be used on fields that are structs implementing the Validify trait. Runs all the nested struct's modifiers and validations. |
*Also works for Vec<T> by running validify on each element.
Validators
All validators also take in a code and message as parameters, their values are must be string literals if specified.
| Validator | Type | Params | Param type | Description |
|---|---|---|---|---|
| String | -- | -- | Checks emails based on this spec. | |
| ip | String | format | Ident (v4/v6) | Checks if the string is an IP address. |
| url | String | -- | -- | Checks if the string is a URL. |
| length | Collection | min, max, equal | LitInt | Checks if the collection length is within the specified params. Works through the HasLen trait. |
| range | Int/Float | min, max | LitFloat | Checks if the value is in the specified range. |
| must_match | Any | value | Ident | Checks if the field matches another field of the struct. The value must be equal to a field identifier on the deriving struct. |
| contains | Collection | value | Lit/Path | Checks if the collection contains the specified value. If used on a K,V collection, it checks whether it has the provided key. |
| contains_not | Collection | value | Lit/Path | Checks if the collection doesn't contain the specified value. If used on a K,V collection, it checks whether it has the provided key. |
| non_control_char | String | -- | -- | Checks if the field contains control characters |
| custom | Function | function | Path | Executes custom validation on the field specified by the end user |
| regex | String | path | Path | Matches the provided regex against the field. Intended to be used with lazy_static by providing a path to an initialised regex. |
| credit_card | String | -- | -- | Checks if the field's value is a valid credit card number |
| phone | String | -- | -- | Checks if the field's value is a valid phone number |
| required | Option<T> | -- | -- | Checks whether the field's value is Some |
| is_in | impl PartialEq | collection | Path | Checks whether the field's value is in the specified collection |
| not_in | impl PartialEq | collection | Path | Checks whether the field's value is not in the specified collection |
| validate | impl Validate | -- | -- | Calls the underlying structs |
| time | NaiveDate[Time] | See below | See below | Performs a check based on the specified op |
Time operators
All time operators can take in inclusive = bool, in_period and the _from_now operators are inclusive by default.
The target param must be a string literal date or a path to an argless function that returns a date[time].
If the target is a string literal, it must contain a format param, as per this.
Accepted interval parameters are seconds, minutes, hours, days, weeks.
The _from_now operators should not use negative duration due to how they validate the inputs,
negative duration for in_period works fine.
| Op | Params | Description |
|---|---|---|
| before | target | Check whether a date[time] is before the target one |
| after | target | Check whether a date[time] is after the target one |
| before_now | -- | Check whether a date[time] is before today[now] |
| after_now | -- | Check whether a date[time] is after the today[now] |
| before_from_now | interval | Check whether a date[time] is before the specified interval from today[now] |
| after_from_now | interval | Check whether a date[time] is after the specified interval from the today[now] |
| in_period | target, interval | Check whether a date[time] falls within a certain period |
Annotate the struct you want to modify and validate with the Validify attribute (if you do not need payload modification, derive the validify::Validate trait):
use Validify;
let mut test = Testor ;
// The magic line
let res = validify;
assert!;
let test = res.unwrap;
// Parent
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// Nested
assert_eq!;
assert_eq!;
Notice how even though field d is an option, the function used to modify the field still takes in &mut String. This is because modifiers and validations are only executed when the field isn't None.
How it works
Every struct annotated with #[derive(Validify)] gets an associated payload struct, e.g.
behind the scenes will generate an intermediary
Note that every field that isn't an option will be an 'optional' required field in the payload. This is done to avoid deserialization errors for missing fields.
- Do note that if a field exists in the incoming client payload, but is of the wrong type, a deserialization error will still occur as the payload is only being validated for whether the necessary fields exist. The same applies for invalid date[time] formats.
Even though the payload struct cannot help with wrong types, it can still prove useful and provide a bit more meaningful error messages when fields are missing.
When a struct contains nested validifies (child structs annotated with #[validify]), all the children in the payload will also be transformed and validated as payloads first.
Validify exposes two methods for validation/modification, validify which takes in the payload and validates its required fields first and validify_self which runs modifications and validations on the original struct, without ever using the payload.
In the context of web, you'll most likely be using validify. As such, the request handler should always take in the payload struct.
The Validify implementation first validates the required fields of the generated payload. If any required fields are missing, no further modification/validation is done and the errors are returned. Next, the payload is transformed to the original struct and modifications and validations are run on it.
Validify's validify method always takes in the generated payload and outputs the original struct if all validations have passed.
The macro automatically implements the Validate and Modify traits in the wrapper trait Validify. This wrapper trait contains only the method validify which:
- Runs the required validations on the payload struct
- Runs modifications on the original
- Runs validations and returns the original struct.
Schema validation
Schema level validations can be performed using the following:
The #[schema_validation] proc macro expands the function to:
This makes schema validations a bit more ergonomic and concise. Like field level validation, schema level validation is performed after modification.
Errors
The main ValidationError is an enum with 2 variants, Field and Schema. Field errors are, as the name suggests, created when fields fail validation and are usually automatically generated unless using custom handlers (custom field validation functions always must return a result whose Err variant is ValidationError).
If you want to provide a message along with the error, you can directly specify it in the attribute (the same goes for the code), for example:
#[validate(contains(value = "something", message = "Does not contain something", code = "MUST_CONTAIN"))]
Keep in mind, when specifying validations this way, all attribute parameters MUST be specified as NameValue pairs. This means that if you write
#[validate(contains("something", message = "Bla"))],
you will get an error, as the parser expects either a single value or multiple name value pairs.
Locations are tracked for each error in a similar manner to JSON pointers. When using custom validation, whatever field name you specify in the returned error will be used in the location for that field.
Original (client payload) field names are also taken into account if they are annotated with #[serde(rename)] on the field level. The struct level rename_all attribute is currently not taken into account, but will eventually be made to work.
Schema errors are usually created by the user in schema validation. The schema_err! and field_err! macros provide an ergonomic way to create errors. All errors are composed to a ValidationErrors struct which contains a vec of all the validation errors.
Examples
With route handler
Big Boi
const WORKING_HOURS: & = &;
const CAREER_LEVEL: & = &;
const STATUSES: & = &;
const CONTRACT_TYPES: & = &;
const ALLOWED_MIME: & = &;
const ALLOWED_DURATIONS: & = &;
const PROFICIENCY: & = &;