Skip to content

Commit

Permalink
Add back multiple custom attributes
Browse files Browse the repository at this point in the history
Closes #308
  • Loading branch information
Keats committed Mar 11, 2024
1 parent 9205787 commit c073d05
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 8 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/.idea
target/
Cargo.lock
testing-bugs/
12 changes: 7 additions & 5 deletions validator_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,13 @@ impl ToTokens for ValidateField {
};

// Custom validation
let custom = if let Some(custom) = self.custom.clone() {
custom_tokens(custom, &field_name, &field_name_str)
} else {
quote!()
};
let mut custom = quote!();
for c in &self.custom {
let tokens = custom_tokens(c.clone(), &field_name, &field_name_str);
custom = quote!(
#tokens
);
}

let nested = if let Some(n) = self.nested {
if n {
Expand Down
7 changes: 4 additions & 3 deletions validator_derive/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ pub struct ValidateField {
pub required_nested: Option<Override<Required>>,
pub url: Option<Override<Url>>,
pub regex: Option<Regex>,
pub custom: Option<Custom>,
#[darling(multiple)]
pub custom: Vec<Custom>,
pub skip: Option<bool>,
pub nested: Option<bool>,
}
Expand All @@ -89,9 +90,9 @@ impl ValidateField {
let field_name = self.ident.clone().expect("Field is not a named field").to_string();
let field_attrs = &current_field.attrs;

if let Some(custom) = &self.custom {
for c in &self.custom {
// If function is not a path
if let Err(e) = &custom.function {
if let Err(e) = &c.function {
abort!(
e.span(), "Invalid attribute #[validate(custom(...))] on field `{}`:", field_name;
note = "Invalid argument for `custom` validator, only paths are allowed";
Expand Down
17 changes: 17 additions & 0 deletions validator_derive_tests/tests/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ fn valid_custom_fn(_: &String) -> Result<(), ValidationError> {
Ok(())
}

fn another_valid_custom_fn(_: &String) -> Result<(), ValidationError> {
Ok(())
}

fn invalid_custom_fn(_: &String) -> Result<(), ValidationError> {
Err(ValidationError::new("meh"))
}
Expand All @@ -21,6 +25,19 @@ fn can_validate_custom_fn_ok() {
assert!(s.validate().is_ok());
}

#[test]
fn can_validate_multiple_custom_fn_ok() {
#[derive(Debug, Validate)]
struct TestStruct {
#[validate(custom(function = valid_custom_fn), custom(function=another_valid_custom_fn))]
val: String,
}

let s = TestStruct { val: "hello".to_string() };

assert!(s.validate().is_ok());
}

#[test]
fn can_fail_custom_fn_validation() {
#[derive(Debug, Validate)]
Expand Down

0 comments on commit c073d05

Please sign in to comment.