appstruct_ir/validation/
form_rules.rs1use super::{IrValidationErrors, push};
2use crate::{AccessRuleIr, ConditionValueIr, EntityIr, FieldIr, FieldTypeIr};
3
4pub fn validate_form_rules(entities: &[EntityIr]) -> Result<(), IrValidationErrors> {
9 let mut errors = Vec::new();
10 for (entity_index, entity) in entities.iter().enumerate() {
11 for (index, field) in entity.fields.iter().enumerate() {
12 let path = format!("entities[{entity_index}].fields[{index}].validation");
13 let rules = &field.validation;
14 if rules.required_when.is_none() && rules.greater_than.is_none() {
15 continue;
16 }
17 if field.primary_key
18 || field.generated.is_some()
19 || entity.is_workflow_field(field)
20 || !unrestricted(field)
21 {
22 push(
23 &mut errors,
24 &path,
25 "validation target must be an ordinary field with unrestricted field access",
26 );
27 }
28 if let Some(rule) = &rules.required_when {
29 if !field.nullable
30 || matches!(field.ty, FieldTypeIr::Json | FieldTypeIr::Relation { .. })
31 {
32 push(
33 &mut errors,
34 &path,
35 "required_when requires a nullable scalar target",
36 );
37 }
38 match entity
39 .fields
40 .iter()
41 .find(|other| other.id == rule.field && other.id != field.id)
42 {
43 Some(other)
44 if unrestricted(other)
45 && match (&other.ty, &rule.equals) {
46 (FieldTypeIr::Boolean, ConditionValueIr::Boolean(_))
47 | (
48 FieldTypeIr::String | FieldTypeIr::Text,
49 ConditionValueIr::String(_),
50 ) => true,
51 (FieldTypeIr::Enum { values }, ConditionValueIr::String(value)) => {
52 values.contains(value)
53 }
54 _ => false,
55 } => {}
56 _ => push(
57 &mut errors,
58 format!("{path}.required_when"),
59 "must reference a different unrestricted sibling boolean/text/enum field with a matching equals value",
60 ),
61 }
62 }
63 if let Some(id) = &rules.greater_than {
64 if !matches!(
65 field.ty,
66 FieldTypeIr::Integer
67 | FieldTypeIr::Bigint
68 | FieldTypeIr::Decimal
69 | FieldTypeIr::Date
70 | FieldTypeIr::Datetime
71 ) {
72 push(
73 &mut errors,
74 &path,
75 "greater_than requires a numeric, date or datetime target",
76 );
77 }
78 if !entity.fields.iter().any(|other| {
79 other.id == *id
80 && other.id != field.id
81 && other.ty == field.ty
82 && unrestricted(other)
83 }) {
84 push(
85 &mut errors,
86 format!("{path}.greater_than"),
87 "must reference a different unrestricted sibling field of the same type",
88 );
89 }
90 }
91 }
92 }
93 if errors.is_empty() {
94 Ok(())
95 } else {
96 Err(IrValidationErrors(errors))
97 }
98}
99
100fn unrestricted(field: &FieldIr) -> bool {
101 [field.read_access.as_ref(), field.write_access.as_ref()]
102 .iter()
103 .all(|rule| rule.is_none_or(|rule| *rule == AccessRuleIr::Public))
104}