-
-
Notifications
You must be signed in to change notification settings - Fork 830
Expand file tree
/
Copy pathvalidation-controller.ts
More file actions
95 lines (82 loc) · 2.42 KB
/
validation-controller.ts
File metadata and controls
95 lines (82 loc) · 2.42 KB
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
/**
* ValidationController - demonstrates validation controller via composition
*
* This controller:
* 1. Manages validation state (isValid, errorMessage)
* 2. Provides method to get validation message data for rendering
* 3. Can trigger validation (ideally on blur)
* 4. Runs a callback provided by the host for validation logic
*/
import { forceUpdate } from '@stencil/core';
import type { ReactiveControllerHost, ReactiveController } from '@stencil/core';
export class ValidationController implements ReactiveController {
private host: ReactiveControllerHost;
private isValid: boolean = true;
private errorMessage: string = '';
private validationCallback?: (value: any) => string | undefined;
constructor(host: ReactiveControllerHost) {
this.host = host;
host.addController(this);
}
// Lifecycle methods
hostDidLoad() {
// Setup validation on component load
this.setupValidation();
}
hostDisconnected() {
// Cleanup if needed
this.cleanupValidation();
}
// Setup validation - can be overridden by host
private setupValidation() {
// Default implementation - can be extended
}
private cleanupValidation() {
// Default implementation - can be extended
}
// Set the validation callback from host
setValidationCallback(callback: (value: any) => string | undefined) {
this.validationCallback = callback;
}
// Validate the value - returns true if valid, false otherwise
validate(value: any): boolean {
if (!this.validationCallback) {
this.isValid = true;
this.errorMessage = '';
forceUpdate(this.host);
return true;
}
const error = this.validationCallback(value);
this.isValid = !error;
this.errorMessage = error || '';
forceUpdate(this.host);
return this.isValid;
}
// Trigger validation on blur
handleBlur(value: any) {
this.validate(value);
}
// Get validation state
getValidationState() {
return {
isValid: this.isValid,
errorMessage: this.errorMessage,
};
}
// Get validation message data for rendering
getValidationMessageData(helperTextId?: string, errorTextId?: string) {
return {
isValid: this.isValid,
errorMessage: this.errorMessage,
helperTextId,
errorTextId,
hasError: !!this.errorMessage,
};
}
// Reset validation state
resetValidation() {
this.isValid = true;
this.errorMessage = '';
forceUpdate(this.host);
}
}