|
|
@@ -0,0 +1,59 @@
|
|
|
+import { reactive } from 'vue'
|
|
|
+
|
|
|
+/** 验证结果 */
|
|
|
+export interface ValidationResult {
|
|
|
+ valid: boolean
|
|
|
+ message?: string
|
|
|
+}
|
|
|
+
|
|
|
+/** 验证函数类型(可携带上下文参数) */
|
|
|
+export type ValidatorFn<T> = (context: T) => ValidationResult
|
|
|
+
|
|
|
+/** Validator 类(支持泛型上下文) */
|
|
|
+export class Validator<T = void> {
|
|
|
+ private nodeRules: Map<string, ValidatorFn<T>> = new Map()
|
|
|
+ public results: Map<string, ValidationResult> = reactive(new Map())
|
|
|
+
|
|
|
+ /** 注册节点验证规则 */
|
|
|
+ register(nodeId: string, validatorFun: ValidatorFn<T>): void {
|
|
|
+ if (typeof validatorFun === 'function') {
|
|
|
+ this.nodeRules.set(nodeId, validatorFun)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 移除节点验证规则 */
|
|
|
+ remove(nodeId: string): void {
|
|
|
+ this.nodeRules.delete(nodeId)
|
|
|
+ this.results.delete(nodeId)
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 执行验证,支持传递上下文 */
|
|
|
+ validate(context: T): { valid: boolean; messages: string[] } {
|
|
|
+ let valid = true
|
|
|
+ const messages: string[] = []
|
|
|
+
|
|
|
+ this.nodeRules.forEach((fun, key) => {
|
|
|
+ const result = fun(context)
|
|
|
+ if (!result.valid) {
|
|
|
+ valid = false
|
|
|
+ this.results.set(key, result)
|
|
|
+ if (result.message) messages.push(result.message)
|
|
|
+ } else {
|
|
|
+ this.results.delete(key)
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ return { valid, messages }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 获取指定节点的结果 */
|
|
|
+ getResult(nodeId: string): ValidationResult | undefined {
|
|
|
+ return this.results.get(nodeId)
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 清空所有规则和结果 */
|
|
|
+ clear(): void {
|
|
|
+ this.nodeRules.clear()
|
|
|
+ this.results.clear()
|
|
|
+ }
|
|
|
+}
|