Files
it-tools-pro/src/composable/validation.ts
T
personal82555 01ff133ac9 IT-TOOLS-PRO v1 - 定制版开发者工具站
12个原创工具(批量条码/二维码识别/在线翻译/OCR/面单设计/AI修图/网站收藏/PDF工具/图片工具/文档转换等)
+ 卡密授权系统(CardAuth对接,30分钟试用,换卡/撤销)
+ 体验优化(中文默认/收藏/最近使用/菜单展开/宽屏/品牌页脚)
2026-10-11 23:58:39 +08:00

95 lines
2.1 KiB
TypeScript

import { type MaybeRef, get } from '@vueuse/core';
import _ from 'lodash';
import { type Ref, reactive, watch } from 'vue';
type ValidatorReturnType = unknown;
type GetErrorMessageReturnType = string;
export interface UseValidationRule<T> {
validator: (value: T) => ValidatorReturnType
getErrorMessage?: (value: T) => GetErrorMessageReturnType
message: string
}
export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
try {
const returnValue = cb();
if (_.isNil(returnValue)) {
return true;
}
return returnValue === false;
}
catch (_) {
return true;
}
}
export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string {
try {
return cb() || '';
}
catch (e: any) {
return e.toString();
}
}
export interface ValidationAttrs {
feedback: string
validationStatus: string | undefined
}
export function useValidation<T>({
source,
rules,
watch: watchRefs = [],
}: {
source: Ref<T>
rules: MaybeRef<UseValidationRule<T>[]>
watch?: Ref<unknown>[]
}) {
const state = reactive<{
message: string
status: undefined | 'error'
isValid: boolean
attrs: ValidationAttrs
}>({
message: '',
status: undefined,
isValid: false,
attrs: {
validationStatus: undefined,
feedback: '',
},
});
watch(
[source, ...watchRefs],
() => {
state.message = '';
state.status = undefined;
for (const rule of get(rules)) {
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value)));
}
else {
state.message = rule.message;
}
state.status = 'error';
}
}
state.isValid = state.status !== 'error';
state.attrs.feedback = state.message;
state.attrs.validationStatus = state.status;
},
{ immediate: true },
);
return state;
}