what-core 1.7.0

Core framework for What - an HTML-first web framework powered by Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Form validation for What
//!
//! Provides server-side form validation using signed hidden fields (JWT).
//! When the engine renders a `<form w-validate>`, it scans inputs for `w-*`
//! validation attributes, serializes rules as a JWT, and injects a hidden field.
//! On submission, the action handler decodes and validates against those rules.

use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::LazyLock;

// Pre-compiled validation regexes
static EMAIL_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$",
    )
    .unwrap()
});
static PHONE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\+?[\d\s\-\(\)]{7,20}$").unwrap());
static DATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$").unwrap());
static TIME_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$").unwrap());

/// Validation rules for a single form field
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FieldRules {
    /// Field is required (non-empty)
    #[serde(default)]
    pub required: bool,

    /// Minimum length
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<usize>,

    /// Maximum length
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<usize>,

    /// Field type validation (email, url, number)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field_type: Option<String>,

    /// Regex pattern to match
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// Another field that must match this one
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_field: Option<String>,

    /// DataStore uniqueness check: "collection.field"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unique: Option<String>,

    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
}

/// All validation rules for a form
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FormRules {
    pub fields: HashMap<String, FieldRules>,
}

/// Result of validating form data against rules
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub errors: HashMap<String, String>,
    pub is_valid: bool,
}

/// Validate form data against rules
pub fn validate_form(data: &HashMap<String, String>, rules: &FormRules) -> ValidationResult {
    let mut errors = HashMap::new();

    for (field_name, field_rules) in &rules.fields {
        let value = data.get(field_name).map(|s| s.as_str()).unwrap_or("");
        let custom_msg = field_rules.error_message.as_deref();

        // Required check
        if field_rules.required && value.is_empty() {
            errors.insert(
                field_name.clone(),
                custom_msg
                    .unwrap_or(&format!("{} is required", field_name))
                    .to_string(),
            );
            continue; // Skip other checks if empty and required
        }

        // Skip other validations if value is empty and not required
        if value.is_empty() {
            continue;
        }

        // Min length
        if let Some(min) = field_rules.min {
            if value.len() < min {
                errors.insert(
                    field_name.clone(),
                    custom_msg
                        .unwrap_or(&format!(
                            "{} must be at least {} characters",
                            field_name, min
                        ))
                        .to_string(),
                );
                continue;
            }
        }

        // Max length
        if let Some(max) = field_rules.max {
            if value.len() > max {
                errors.insert(
                    field_name.clone(),
                    custom_msg
                        .unwrap_or(&format!(
                            "{} must be at most {} characters",
                            field_name, max
                        ))
                        .to_string(),
                );
                continue;
            }
        }

        // Type validation
        if let Some(ref field_type) = field_rules.field_type {
            let valid = match field_type.as_str() {
                "email" => EMAIL_RE.is_match(value),
                "url" => url::Url::parse(value).is_ok(),
                "number" => value.parse::<f64>().is_ok(),
                "phone" => PHONE_RE.is_match(value),
                "date" => DATE_RE.is_match(value),
                "time" => TIME_RE.is_match(value),
                _ => true,
            };
            if !valid {
                errors.insert(
                    field_name.clone(),
                    custom_msg
                        .unwrap_or(&format!("{} must be a valid {}", field_name, field_type))
                        .to_string(),
                );
                continue;
            }
        }

        // Regex pattern (with size/complexity limits to prevent ReDoS)
        if let Some(ref pattern) = field_rules.pattern {
            if pattern.len() > 512 {
                errors.insert(
                    field_name.clone(),
                    custom_msg
                        .unwrap_or(&format!("{}: validation pattern too long", field_name))
                        .to_string(),
                );
                continue;
            }
            if let Ok(re) = regex::RegexBuilder::new(pattern)
                .size_limit(1 << 20) // 1MB compiled size limit
                .build()
            {
                if !re.is_match(value) {
                    errors.insert(
                        field_name.clone(),
                        custom_msg
                            .unwrap_or(&format!(
                                "{} does not match the required format",
                                field_name
                            ))
                            .to_string(),
                    );
                    continue;
                }
            }
        }

        // Match field
        if let Some(ref match_name) = field_rules.match_field {
            let other_value = data.get(match_name).map(|s| s.as_str()).unwrap_or("");
            if value != other_value {
                errors.insert(
                    field_name.clone(),
                    custom_msg
                        .unwrap_or(&format!("{} must match {}", field_name, match_name))
                        .to_string(),
                );
            }
        }

        // Note: unique check requires DataStore access - handled in server/mod.rs
    }

    let is_valid = errors.is_empty();
    ValidationResult { errors, is_valid }
}

/// Parse validation rules from form HTML by scanning for w-* attributes on inputs
pub fn parse_form_rules(form_html: &str) -> FormRules {
    let mut fields = HashMap::new();

    // Use regex to find input/textarea/select elements with w-* attributes
    // The scraper crate lowercases attributes, so we work with the raw HTML
    let input_re =
        regex::Regex::new(r#"<(?:input|textarea|select)\s[^>]*?name\s*=\s*"([^"]+)"[^>]*>"#)
            .unwrap();

    for cap in input_re.captures_iter(form_html) {
        let field_name = cap[1].to_string();
        let tag_html = cap[0].to_string();

        let mut rules = FieldRules::default();
        let mut has_rules = false;

        if tag_html.contains("w-required") {
            rules.required = true;
            has_rules = true;
        }

        if let Some(min_cap) = regex::Regex::new(r#"w-min\s*=\s*"(\d+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.min = min_cap[1].parse().ok();
            has_rules = true;
        }

        if let Some(max_cap) = regex::Regex::new(r#"w-max\s*=\s*"(\d+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.max = max_cap[1].parse().ok();
            has_rules = true;
        }

        if let Some(type_cap) = regex::Regex::new(r#"w-type\s*=\s*"([^"]+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.field_type = Some(type_cap[1].to_string());
            has_rules = true;
        }

        if let Some(pattern_cap) = regex::Regex::new(r#"w-pattern\s*=\s*"([^"]+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.pattern = Some(pattern_cap[1].to_string());
            has_rules = true;
        }

        if let Some(match_cap) = regex::Regex::new(r#"w-match\s*=\s*"([^"]+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.match_field = Some(match_cap[1].to_string());
            has_rules = true;
        }

        if let Some(unique_cap) = regex::Regex::new(r#"w-unique\s*=\s*"([^"]+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.unique = Some(unique_cap[1].to_string());
            has_rules = true;
        }

        if let Some(error_cap) = regex::Regex::new(r#"w-error\s*=\s*"([^"]+)""#)
            .ok()
            .and_then(|re| re.captures(&tag_html))
        {
            rules.error_message = Some(error_cap[1].to_string());
        }

        if has_rules {
            fields.insert(field_name, rules);
        }
    }

    FormRules { fields }
}

/// Encode validation rules as a JWT for embedding in a hidden form field
pub fn encode_rules(rules: &FormRules, secret: &str) -> Option<String> {
    use jsonwebtoken::{EncodingKey, Header, encode};
    encode(
        &Header::default(),
        rules,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .ok()
}

/// Decode and verify validation rules from a JWT hidden field
pub fn decode_rules(token: &str, secret: &str) -> Option<FormRules> {
    use jsonwebtoken::{DecodingKey, Validation, decode};
    let mut validation = Validation::default();
    validation.required_spec_claims.clear();
    validation.validate_exp = false;

    decode::<FormRules>(
        token,
        &DecodingKey::from_secret(secret.as_bytes()),
        &validation,
    )
    .ok()
    .map(|data| data.claims)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_required_present() {
        let rules = FormRules {
            fields: HashMap::from([(
                "name".to_string(),
                FieldRules {
                    required: true,
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::from([("name".to_string(), "Alice".to_string())]);
        let result = validate_form(&data, &rules);
        assert!(result.is_valid);
    }

    #[test]
    fn test_validate_required_missing() {
        let rules = FormRules {
            fields: HashMap::from([(
                "name".to_string(),
                FieldRules {
                    required: true,
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::new();
        let result = validate_form(&data, &rules);
        assert!(!result.is_valid);
        assert!(result.errors.contains_key("name"));
    }

    #[test]
    fn test_validate_min_length() {
        let rules = FormRules {
            fields: HashMap::from([(
                "password".to_string(),
                FieldRules {
                    min: Some(8),
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::from([("password".to_string(), "short".to_string())]);
        let result = validate_form(&data, &rules);
        assert!(!result.is_valid);
        assert!(
            result
                .errors
                .get("password")
                .unwrap()
                .contains("at least 8")
        );
    }

    #[test]
    fn test_validate_max_length() {
        let rules = FormRules {
            fields: HashMap::from([(
                "bio".to_string(),
                FieldRules {
                    max: Some(5),
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::from([("bio".to_string(), "too long text".to_string())]);
        let result = validate_form(&data, &rules);
        assert!(!result.is_valid);
    }

    #[test]
    fn test_validate_email_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "email".to_string(),
                FieldRules {
                    field_type: Some("email".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let valid = HashMap::from([("email".to_string(), "user@example.com".to_string())]);
        assert!(validate_form(&valid, &rules).is_valid);

        let invalid = HashMap::from([("email".to_string(), "notanemail".to_string())]);
        assert!(!validate_form(&invalid, &rules).is_valid);
    }

    #[test]
    fn test_validate_url_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "website".to_string(),
                FieldRules {
                    field_type: Some("url".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let valid = HashMap::from([("website".to_string(), "https://example.com".to_string())]);
        assert!(validate_form(&valid, &rules).is_valid);

        let invalid = HashMap::from([("website".to_string(), "not-a-url".to_string())]);
        assert!(!validate_form(&invalid, &rules).is_valid);
    }

    #[test]
    fn test_validate_number_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "age".to_string(),
                FieldRules {
                    field_type: Some("number".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let valid = HashMap::from([("age".to_string(), "25".to_string())]);
        assert!(validate_form(&valid, &rules).is_valid);

        let invalid = HashMap::from([("age".to_string(), "abc".to_string())]);
        assert!(!validate_form(&invalid, &rules).is_valid);
    }

    #[test]
    fn test_validate_pattern() {
        let rules = FormRules {
            fields: HashMap::from([(
                "zip".to_string(),
                FieldRules {
                    pattern: Some(r"^\d{5}$".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let valid = HashMap::from([("zip".to_string(), "12345".to_string())]);
        assert!(validate_form(&valid, &rules).is_valid);

        let invalid = HashMap::from([("zip".to_string(), "1234".to_string())]);
        assert!(!validate_form(&invalid, &rules).is_valid);
    }

    #[test]
    fn test_validate_match_field() {
        let rules = FormRules {
            fields: HashMap::from([(
                "confirm_password".to_string(),
                FieldRules {
                    match_field: Some("password".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let valid = HashMap::from([
            ("password".to_string(), "secret".to_string()),
            ("confirm_password".to_string(), "secret".to_string()),
        ]);
        assert!(validate_form(&valid, &rules).is_valid);

        let invalid = HashMap::from([
            ("password".to_string(), "secret".to_string()),
            ("confirm_password".to_string(), "different".to_string()),
        ]);
        assert!(!validate_form(&invalid, &rules).is_valid);
    }

    #[test]
    fn test_validate_custom_error_message() {
        let rules = FormRules {
            fields: HashMap::from([(
                "name".to_string(),
                FieldRules {
                    required: true,
                    error_message: Some("Please enter your name".to_string()),
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::new();
        let result = validate_form(&data, &rules);
        assert_eq!(result.errors.get("name").unwrap(), "Please enter your name");
    }

    #[test]
    fn test_validate_empty_non_required_skips() {
        let rules = FormRules {
            fields: HashMap::from([(
                "bio".to_string(),
                FieldRules {
                    min: Some(10),
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::from([("bio".to_string(), "".to_string())]);
        let result = validate_form(&data, &rules);
        assert!(result.is_valid); // Empty is OK when not required
    }

    #[test]
    fn test_parse_form_rules_basic() {
        let html = r#"<form w-validate>
            <input type="text" name="username" w-required w-min="3" w-max="20">
            <input type="email" name="email" w-required w-type="email">
            <input type="submit" value="Submit">
        </form>"#;
        let rules = parse_form_rules(html);
        assert_eq!(rules.fields.len(), 2);

        let username = rules.fields.get("username").unwrap();
        assert!(username.required);
        assert_eq!(username.min, Some(3));
        assert_eq!(username.max, Some(20));

        let email = rules.fields.get("email").unwrap();
        assert!(email.required);
        assert_eq!(email.field_type.as_deref(), Some("email"));
    }

    #[test]
    fn test_parse_form_rules_with_pattern() {
        let html = r#"<input name="zip" w-pattern="^\d{5}$" w-error="Invalid zip code">"#;
        let rules = parse_form_rules(html);
        let zip = rules.fields.get("zip").unwrap();
        assert_eq!(zip.pattern.as_deref(), Some(r"^\d{5}$"));
        assert_eq!(zip.error_message.as_deref(), Some("Invalid zip code"));
    }

    #[test]
    fn test_parse_form_rules_with_match() {
        let html = r#"<input name="confirm" w-match="password" w-required>"#;
        let rules = parse_form_rules(html);
        let confirm = rules.fields.get("confirm").unwrap();
        assert!(confirm.required);
        assert_eq!(confirm.match_field.as_deref(), Some("password"));
    }

    #[test]
    fn test_encode_decode_rules_roundtrip() {
        let rules = FormRules {
            fields: HashMap::from([
                (
                    "name".to_string(),
                    FieldRules {
                        required: true,
                        min: Some(2),
                        ..Default::default()
                    },
                ),
                (
                    "email".to_string(),
                    FieldRules {
                        required: true,
                        field_type: Some("email".to_string()),
                        ..Default::default()
                    },
                ),
            ]),
        };

        let secret = "test-secret-key";
        let token = encode_rules(&rules, secret).expect("encoding should work");
        let decoded = decode_rules(&token, secret).expect("decoding should work");

        assert_eq!(decoded.fields.len(), 2);
        assert!(decoded.fields.get("name").unwrap().required);
        assert_eq!(decoded.fields.get("name").unwrap().min, Some(2));
        assert_eq!(
            decoded.fields.get("email").unwrap().field_type.as_deref(),
            Some("email")
        );
    }

    #[test]
    fn test_decode_rules_wrong_secret() {
        let rules = FormRules {
            fields: HashMap::from([(
                "name".to_string(),
                FieldRules {
                    required: true,
                    ..Default::default()
                },
            )]),
        };
        let token = encode_rules(&rules, "secret1").unwrap();
        let result = decode_rules(&token, "secret2");
        assert!(result.is_none());
    }

    #[test]
    fn test_decode_rules_invalid_token() {
        let result = decode_rules("not.a.valid.token", "secret");
        assert!(result.is_none());
    }

    // --- New type validation tests ---

    #[test]
    fn test_validate_phone_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "phone".to_string(),
                FieldRules {
                    field_type: Some("phone".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid phone numbers
        for phone in &[
            "+1 555-123-4567",
            "(555) 123-4567",
            "5551234567",
            "+44 20 7946 0958",
        ] {
            let data = HashMap::from([("phone".to_string(), phone.to_string())]);
            assert!(
                validate_form(&data, &rules).is_valid,
                "Expected valid: {}",
                phone
            );
        }
        // Invalid phone numbers
        for phone in &["abc", "12", "+1"] {
            let data = HashMap::from([("phone".to_string(), phone.to_string())]);
            assert!(
                !validate_form(&data, &rules).is_valid,
                "Expected invalid: {}",
                phone
            );
        }
    }

    #[test]
    fn test_validate_date_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "date".to_string(),
                FieldRules {
                    field_type: Some("date".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid dates
        for date in &["2024-01-15", "2024-12-31", "2000-06-01"] {
            let data = HashMap::from([("date".to_string(), date.to_string())]);
            assert!(
                validate_form(&data, &rules).is_valid,
                "Expected valid: {}",
                date
            );
        }
        // Invalid dates
        for date in &["2024-13-01", "2024-00-15", "24-01-15", "not-a-date"] {
            let data = HashMap::from([("date".to_string(), date.to_string())]);
            assert!(
                !validate_form(&data, &rules).is_valid,
                "Expected invalid: {}",
                date
            );
        }
    }

    #[test]
    fn test_validate_time_type() {
        let rules = FormRules {
            fields: HashMap::from([(
                "time".to_string(),
                FieldRules {
                    field_type: Some("time".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid times
        for time in &["00:00", "23:59", "12:30", "09:15:30"] {
            let data = HashMap::from([("time".to_string(), time.to_string())]);
            assert!(
                validate_form(&data, &rules).is_valid,
                "Expected valid: {}",
                time
            );
        }
        // Invalid times
        for time in &["24:00", "12:60", "abc", "9:5"] {
            let data = HashMap::from([("time".to_string(), time.to_string())]);
            assert!(
                !validate_form(&data, &rules).is_valid,
                "Expected invalid: {}",
                time
            );
        }
    }

    #[test]
    fn test_validate_email_rfc5322() {
        let rules = FormRules {
            fields: HashMap::from([(
                "email".to_string(),
                FieldRules {
                    field_type: Some("email".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid emails
        for email in &["user@example.com", "user+tag@sub.domain.co", "a@b.io"] {
            let data = HashMap::from([("email".to_string(), email.to_string())]);
            assert!(
                validate_form(&data, &rules).is_valid,
                "Expected valid: {}",
                email
            );
        }
        // Invalid emails
        for email in &["notanemail", "@no-local.com", "user@", "user@.com"] {
            let data = HashMap::from([("email".to_string(), email.to_string())]);
            assert!(
                !validate_form(&data, &rules).is_valid,
                "Expected invalid: {}",
                email
            );
        }
    }

    #[test]
    fn test_validate_url_proper() {
        let rules = FormRules {
            fields: HashMap::from([(
                "website".to_string(),
                FieldRules {
                    field_type: Some("url".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid URLs
        for url in &[
            "https://example.com",
            "http://localhost:3000",
            "ftp://files.example.com/doc.txt",
        ] {
            let data = HashMap::from([("website".to_string(), url.to_string())]);
            assert!(
                validate_form(&data, &rules).is_valid,
                "Expected valid: {}",
                url
            );
        }
        // Invalid URLs
        for url in &["not-a-url", "example.com", "://missing-scheme"] {
            let data = HashMap::from([("website".to_string(), url.to_string())]);
            assert!(
                !validate_form(&data, &rules).is_valid,
                "Expected invalid: {}",
                url
            );
        }
    }

    #[test]
    fn test_oversized_pattern_rejected() {
        // Pattern longer than 512 chars should be rejected
        let long_pattern = "a".repeat(600);
        let rules = FormRules {
            fields: HashMap::from([(
                "code".to_string(),
                FieldRules {
                    pattern: Some(long_pattern),
                    ..Default::default()
                },
            )]),
        };
        let data = HashMap::from([("code".to_string(), "abc".to_string())]);
        let result = validate_form(&data, &rules);
        assert!(!result.is_valid, "Oversized pattern should be rejected");
        assert!(
            result
                .errors
                .values()
                .any(|e| e.contains("pattern too long")),
            "Error message should mention pattern too long"
        );
    }

    #[test]
    fn test_normal_pattern_still_works() {
        let rules = FormRules {
            fields: HashMap::from([(
                "code".to_string(),
                FieldRules {
                    pattern: Some(r"^[A-Z]{3}\d{3}$".to_string()),
                    ..Default::default()
                },
            )]),
        };
        // Valid
        let data = HashMap::from([("code".to_string(), "ABC123".to_string())]);
        assert!(validate_form(&data, &rules).is_valid);
        // Invalid
        let data = HashMap::from([("code".to_string(), "abc".to_string())]);
        assert!(!validate_form(&data, &rules).is_valid);
    }
}