Respect constant names in validation rules
greyblake opened this issue · comments
As for now it's not possible to use constant name in the most of validation rules.
Examples
use nutype::nutype;
const NAME_MIN_LEN: usize = 3;
#[nutype(
sanitize(trim)
validate(min_len = NAME_MIN_LEN)
)]
pub struct Name(String);
previous errors
error: Expected usize, got `NAME_MIN_LEN`
--> src/main.rs:12:24
|
12 | validate(min_len = NAME_MIN_LEN)
Or
const AMOUNT_MAX: f64 = 42.0;
#[nutype(
validate(max = 42.0)
)]
pub struct Amount(f64);
error: Expected f64, got `AMOUNT_MAX`
--> src/main.rs:11:20
|
11 | validate(max = AMOUNT_MAX)
Reasons
The original reason for this was to be able to validate correctness of the given values at compile time.
For example, if min
is greater than max
, the following example does not compile:
#[nutype(
validate(max = 10, min = 20)
)]
pub struct Number(i32)
error: `min` cannot be greater than `max`.
Sometimes we all need a little break.
--> src/main.rs:9:14
|
9 | validate(max = 10, min = 20)
| ^^^
Desired
- Allow specifying the values for the validation rules as named constants
- Keep the validation, if it can be executed at compile time
- Consider generating extra tests to ensure the the dynamic (named constant) values still make sense at runtime.
- Use this trick to ensure that
max
is greater thatmin
: TedDriggs/darling#244 (comment)