use laravel::Application;
use laravel::config::{Env, session::Driver};
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::Json;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{Field, Rule, RuleError, Rules, Valid, Validate, ValidationRule};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::support::Invalid;
#[derive(Debug, Deserialize, Serialize, Validate)]
struct Address {
#[validate(required, max_length = 5)]
city: String,
#[serde(alias = "nation")]
country: Option<String>,
#[validate(required_if("country", "US"), max_length = 5)]
postal_code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
struct Shipment {
delivery: String,
#[serde(default)]
quantity: u32,
#[serde(alias = "destination")]
#[validate(required_if("delivery", "ship"), nested)]
address: Option<Address>,
#[validate(prohibited_if("delivery", "pickup"))]
instructions: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct Checkout {
#[validate(min_items = 1, max_items = 2, each)]
shipments: Vec<Shipment>,
#[validate(max_items = 3, distinct, each(required))]
tags: Vec<String>,
phone: Option<String>,
contact_name: Option<String>,
#[validate(required_with("phone", "contact_name"), max_length = 5)]
contact_code: Option<String>,
#[validate(confirmed)]
password: Option<String>,
}
async fn store(Valid(input): Valid<Checkout>) -> Json<Checkout> {
Json(input)
}
fn app() -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
config.session.driver = Driver::Memory;
})
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/checkout", store);
});
routing.web(|route: &mut Router| {
route.post("/checkout", store);
});
})
.create()
}
#[tokio::test]
async fn nested_and_list_rules_collect_errors_with_scoped_conditions() {
app().post("/api/checkout").json(json!({
"shipments":[
{"delivery":"ship", "destination":{"city":"longer", "nation":"US"}},
{"delivery":"pickup", "instructions":"do this"}
],
"tags":["rust", "rust"], "phone":"123", "password":"secret", "password_confirmation":"different"
})).await.assert_status(422).assert_nothing_reported()
.assert_json(json!({"errors": {
"shipments.0.destination.city":["The shipments.0.destination.city field must not be greater than 5 characters."],
"shipments.0.destination.postal_code":["The shipments.0.destination.postal_code field is required when shipments.0.destination.country is US."],
"shipments.1.instructions":["The shipments.1.instructions field is prohibited when shipments.1.delivery is pickup."],
"tags":["The tags field has a duplicate value."],
"contact_code":["The contact code field is required when phone / contact name is present."],
"password":["The password field confirmation does not match."]
}}));
}
#[tokio::test]
async fn sparse_forms_validate_each_objects_conditions_without_leaking_between_entries() {
let app = app();
app.post("/api/checkout")
.form([
("shipments[7][delivery]", "ship"),
("shipments[7][destination][city]", "Paris"),
("shipments[7][destination][country]", "FR"),
("shipments[2][delivery]", "pickup"),
("tags[4]", "rust"),
("password", "secret"),
("password_confirmation", "secret"),
])
.await
.assert_ok()
.assert_json(json!({"shipments":[
{"delivery":"pickup", "address":null},
{"delivery":"ship", "address":{"city":"Paris", "country":"FR", "postal_code":null}}
]}));
app.post("/api/checkout")
.form([
("shipments[7][delivery]", "ship"),
("shipments[2][delivery]", "pickup"),
("tags[4]", "rust"),
])
.await
.assert_json(json!({"errors": {
"shipments.7.address":["The shipments.7.address field is required when shipments.7.delivery is ship."]
}}));
}
#[tokio::test]
async fn nested_object_errors_reach_redirects_and_old_input() {
app()
.post("/checkout")
.header("referer", "/form")
.form([
("shipments[7][delivery]", "ship"),
("shipments[7][address][city]", "longer"),
("tags[4]", "rust"),
])
.await
.assert_redirect_to("/form")
.assert_invalid(&["shipments.7.address.city"])
.assert_session_has("_old_input.shipments.7.address.city", "longer");
}
#[tokio::test]
async fn collection_boundaries_and_empty_lists_are_checked_without_required() {
let app = app();
app.post("/api/checkout")
.json(json!({"shipments":[], "tags":[]}))
.await
.assert_json(json!({"errors":{"shipments":["The shipments field must have at least 1 items."]}}));
app.post("/api/checkout")
.json(json!({
"shipments":[{"delivery":"pickup"},{"delivery":"pickup"},{"delivery":"pickup", "quantity":"many"}],
"tags":["a","b","c","d"]
}))
.await
.assert_json(json!({"errors":{
"shipments":["The shipments field must not have more than 2 items."],
"tags":["The tags field must not have more than 3 items."],
"shipments.2.quantity":["The shipments.2.quantity field must be an integer."]
}}));
app.post("/api/checkout")
.json(json!({"shipments":[{"delivery":"pickup"}], "tags":[]}))
.await
.assert_ok();
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Generic<T> {
#[validate]
value: T,
}
impl<T: laravel::validation::Validate> laravel::validation::ValidatesRequest for Generic<T> {
async fn authorize(_: &laravel::http::Request) -> laravel::Result<bool> {
Ok(true)
}
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Recursive {
#[validate(required)]
name: String,
#[validate]
child: Option<Box<Recursive>>,
}
#[tokio::test]
async fn nested_generic_and_recursive_types_validate_only_submitted_objects() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/nested", |Valid(_): Valid<Generic<Recursive>>| async { "ok" });
});
})
.create();
for value in [
json!({"name":"root"}),
json!({"name":"root", "child":null}),
json!({"name":"root", "child":{"name":"leaf"}}),
] {
app.post("/api/nested").json(json!({"value":value})).await.assert_ok();
}
app.post("/api/nested")
.json(json!({"value":{"name":"root", "child":{}}}))
.await
.assert_json(json!({"errors":{"value.child.name":["The value.child.name field is required."]}}));
for value in [json!(42), json!([]), json!("bad")] {
app.post("/api/nested")
.json(json!({"value":value}))
.await
.assert_json(json!({"errors":{"value":["The value field must be an array."]}}));
}
app.post("/api/nested")
.json(json!({}))
.await
.assert_json(json!({"errors":{"value":["The value field is required."]}}));
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct BareProfile {
delivery: String,
#[serde(alias = "location")]
#[validate]
#[validate(required_if("delivery", "ship"))]
address: Option<Address>,
#[serde(alias = "places")]
#[validate]
#[validate(max_items = 2)]
previous_addresses: Option<Vec<Option<Address>>>,
}
#[tokio::test]
async fn bare_validation_combines_child_rules_with_parent_rules_aliases_and_nullable_lists() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/profile", |Valid(input): Valid<BareProfile>| async { Json(input) });
});
})
.create();
for body in [
json!({"delivery":"pickup"}),
json!({"delivery":"pickup", "address":null, "previous_addresses":null}),
json!({"delivery":"ship", "location":{"city":"Paris", "nation":"FR"}, "places":[null, {"city":"Paris"}]}),
] {
app.post("/api/profile").json(&body).await.assert_ok();
}
let response = app
.post("/api/profile")
.json(json!({
"delivery":"ship", "location":{},
"places":{"7":{"city":"longer", "nation":"US"}, "2":null}
}))
.await;
response.assert_status(422).assert_nothing_reported();
assert_eq!(
response.json()["errors"],
json!({
"location":["The location field is required when delivery is ship."],
"places.7.city":["The places.7.city field must not be greater than 5 characters."],
"places.7.postal_code":["The places.7.postal_code field is required when places.7.country is US."]
})
);
let response = app
.post("/api/profile")
.json(json!({
"delivery":"pickup", "places":[{"city":"Paris"}, {"city":"Paris"}, {"city":"Paris"}]
}))
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({
"places":["The places field must not have more than 2 items."]
})
);
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validation is exercised")]
struct RequiredNested {
#[validate(required, nested)]
address: Option<Address>,
}
#[tokio::test]
async fn required_nested_empty_object_stops_child_rules() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/address", |Valid(_): Valid<RequiredNested>| async { "ok" });
});
})
.create();
for body in [json!({}), json!({"address":null}), json!({"address":{}})] {
app.post("/api/address")
.json(&body)
.await
.assert_json(json!({"errors":{
"address":["The address field is required."]
}}))
.assert_valid(&["address.city", "address.country", "address.postal_code"]);
}
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[validate(anyone)]
struct ConditionalScalars {
enabled: bool,
count: u32,
#[validate(required_if("enabled", false))]
fallback: Option<String>,
#[validate(required_if("enabled", true))]
label: Option<String>,
#[validate(required_if("count", 2))]
explanation: Option<String>,
}
#[tokio::test]
async fn conditional_scalar_values_use_request_form_conversions_without_recovery_values() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/scalars", |Valid(input): Valid<ConditionalScalars>| async {
Json(input)
});
});
})
.create();
app.post("/api/scalars")
.form([("enabled", "on"), ("count", "02")])
.await
.assert_invalid(&["label", "explanation"]);
app.post("/api/scalars")
.form([("enabled", "off"), ("count", "1"), ("fallback", "because")])
.await
.assert_ok();
app.post("/api/scalars")
.json(json!({"enabled":true,"count":2,"label":"x","explanation":"x"}))
.await
.assert_ok();
app.post("/api/scalars")
.form([("enabled", "broken"), ("count", "broken")])
.await
.assert_invalid(&["enabled", "count"])
.assert_valid(&["label", "explanation", "fallback"]);
}
struct SameAsSibling;
impl ValidationRule for SameAsSibling {
async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
if field.value == field.get("expected") {
Ok(())
} else {
Err(RuleError::invalid(format!(
"The {} field must match its sibling.",
field.name
)))
}
}
}
#[derive(Debug, Deserialize, Validate)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Siblings {
#[validate(SameAsSibling)]
actual: String,
}
#[derive(Debug, Deserialize, Validate)]
#[validate(anyone)]
#[expect(dead_code, reason = "only validation is exercised")]
struct Scoped {
#[validate(nested)]
object: Siblings,
#[validate(each)]
items: Vec<Siblings>,
}
#[tokio::test]
async fn custom_rule_sibling_access_uses_the_current_object_scope() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.post("/scoped", |Valid(_): Valid<Scoped>| async { "ok" });
});
})
.create();
app.post("/api/scoped")
.json(json!({"expected":"root", "object":{"expected":"one", "actual":"one"},
"items":[{"expected":"two", "actual":"two"},{"expected":"three", "actual":"wrong"}]}))
.await
.assert_json(json!({"errors":{"items.1.actual":["The items.1.actual field must match its sibling."]}}));
}
#[tokio::test]
async fn distinct_compares_original_json_values_strictly_and_ignores_object_key_order() {
let rules = Rules::new().field("items", [Rule::distinct()]);
for values in [
json!(["a", "a"]),
json!([{"a":1,"b":2},{"b":2,"a":1}]),
json!([0.0, -0.0]),
json!([[1], [1]]),
json!([null, null]),
] {
assert!(
rules
.validate(json!({"items":values}).as_object().unwrap())
.await
.is_err()
);
}
for values in [json!([1, "1", 1.0]), json!(["a", "A"]), json!([])] {
rules
.validate(json!({"items":values}).as_object().unwrap())
.await
.unwrap();
}
for text in [r#"[1.0,1.00]"#, r#"[1.00,1e0]"#, r#"[{"n":0.00},{"n":-0.0}]"#] {
let values: Value = serde_json::from_str(text).unwrap();
assert!(
rules
.validate(json!({"items":values}).as_object().unwrap())
.await
.is_err()
);
}
for text in [
r#"[1,1.00]"#,
r#"[0.0,1e-1000]"#,
r#"[0.10000000000000001,0.10000000000000002]"#,
] {
let values: Value = serde_json::from_str(text).unwrap();
rules
.validate(json!({"items":values}).as_object().unwrap())
.await
.unwrap();
}
let input = json!({"items":(0..10_000).collect::<Vec<_>>()});
rules.validate(input.as_object().unwrap()).await.unwrap();
}
#[tokio::test]
async fn collection_and_conditional_semantics_match_classic_fixtures() {
let fixtures: Vec<serde_json::Value> =
serde_json::from_str(include_str!("fixtures/validation-composition.json")).unwrap();
for fixture in fixtures {
let kind = fixture["kind"].as_str().unwrap();
let rules = match kind {
"min_items" => Rules::new().field("value", [Rule::min_items(1)]),
"max_items" => Rules::new().field("value", [Rule::max_items(2)]),
"distinct" => Rules::new().field("value", [Rule::distinct()]),
"required_if" => Rules::new()
.nullable("value")
.field("value", [Rule::required_if("delivery", "ship"), Rule::string()]),
"required_if_number" => Rules::new()
.nullable("value")
.field("value", [Rule::required_if("count", 2), Rule::string()]),
"required_if_zero" => Rules::new()
.nullable("value")
.field("value", [Rule::required_if("count", 0), Rule::string()]),
"required_if_bool" => Rules::new()
.nullable("value")
.field("value", [Rule::required_if("enabled", true), Rule::string()]),
"required_if_false" => Rules::new()
.nullable("value")
.field("value", [Rule::required_if("enabled", false), Rule::string()]),
"required_if_null" => Rules::new().nullable("value").field(
"value",
[Rule::required_if("delivery", serde_json::Value::Null), Rule::string()],
),
"prohibited_if_null" => Rules::new().nullable("value").field(
"value",
[Rule::prohibited_if("delivery", serde_json::Value::Null), Rule::string()],
),
"required_with" => Rules::new().nullable("value").field(
"value",
[Rule::required_with(["phone", "contact_name"]), Rule::string()],
),
"required_with_not_nullable" => {
Rules::new().field("value", [Rule::required_with(["phone"]), Rule::string()])
}
"prohibited_if" => Rules::new()
.nullable("value")
.field("value", [Rule::prohibited_if("delivery", "pickup"), Rule::string()]),
"prohibited_if_only" => Rules::new().field("value", [Rule::prohibited_if("delivery", "pickup")]),
"confirmed" => Rules::new().field("value", [Rule::confirmed()]),
_ => unreachable!("fixture kind"),
};
let result = rules.validate(fixture["input"].as_object().unwrap()).await;
if kind == "distinct" {
assert_eq!(
result.is_ok(),
fixture["passes"].as_bool().unwrap(),
"{}",
fixture["name"]
);
} else {
assert_eq!(
serde_json::to_value(result.err().map(|error| error.invalid().clone()).unwrap_or_default()).unwrap(),
fixture["errors"],
"{}",
fixture["name"]
);
}
}
}
#[tokio::test]
async fn a_later_nested_or_each_replaces_the_earlier_one() {
let rules = Rules::new().each::<Address>("address").nested::<Address>("address");
let input = json!({"address": {"city": "longer"}});
let Err(laravel::validation::ValidationError::Invalid(errors)) = rules.validate(input.as_object().unwrap()).await
else {
panic!("the city is too long");
};
assert_eq!(
errors.errors().keys().collect::<Vec<_>>(),
["address.city"],
"{:?}",
errors.errors()
);
let rules = Rules::new().nested::<Address>("addresses").each::<Address>("addresses");
let input = json!({"addresses": [{"city": "Paris"}]});
rules.validate(input.as_object().unwrap()).await.unwrap();
}
#[tokio::test]
async fn list_entry_settings_without_list_rules_fail_validation() {
for rules in [
Rules::new().field("tags", [Rule::required()]).item_label("tags", "tag"),
Rules::new().nested::<Address>("tags").nullable_items("tags"),
] {
let input = json!({"tags": ["rust"]});
let Err(laravel::validation::ValidationError::Failed(error)) = rules.validate(input.as_object().unwrap()).await
else {
panic!("the settings have no entries to apply to");
};
assert!(error.to_string().contains("no `each` or `each_value`"), "{error}");
}
}