Skip to content

Commit c6c004c

Browse files
committed
fix: useForm support dynamic add rule #4498
close #4498 #4557
1 parent e9a44b9 commit c6c004c

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

components/form/useForm.ts

+27-8
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,33 @@ function useForm(
119119
clearValidate: (names?: namesType) => void;
120120
} {
121121
const initialModel = cloneDeep(unref(modelRef));
122-
let validateInfos: validateInfos = {};
122+
const validateInfos = reactive<validateInfos>({});
123123

124124
const rulesKeys = computed(() => {
125125
return Object.keys(unref(rulesRef));
126126
});
127127

128-
rulesKeys.value.forEach(key => {
129-
validateInfos[key] = {
130-
autoLink: false,
131-
required: isRequired(unref(rulesRef)[key]),
132-
};
133-
});
134-
validateInfos = reactive(validateInfos);
128+
watch(
129+
rulesKeys,
130+
() => {
131+
const newValidateInfos = {};
132+
rulesKeys.value.forEach(key => {
133+
newValidateInfos[key] = validateInfos[key] || {
134+
autoLink: false,
135+
required: isRequired(unref(rulesRef)[key]),
136+
};
137+
delete validateInfos[key];
138+
});
139+
for (const key in validateInfos) {
140+
if (Object.prototype.hasOwnProperty.call(validateInfos, key)) {
141+
delete validateInfos[key];
142+
}
143+
}
144+
Object.assign(validateInfos, newValidateInfos);
145+
},
146+
{ immediate: true },
147+
);
148+
135149
const resetFields = (newValues: Props) => {
136150
Object.assign(unref(modelRef), {
137151
...cloneDeep(initialModel),
@@ -251,6 +265,9 @@ function useForm(
251265
},
252266
!!option.validateFirst,
253267
);
268+
if (!validateInfos[name]) {
269+
return promise.catch((e: any) => e);
270+
}
254271
validateInfos[name].validateStatus = 'validating';
255272
promise
256273
.catch((e: any) => e)
@@ -327,7 +344,9 @@ function useForm(
327344
validate(names, { trigger: 'change' });
328345
oldModel = cloneDeep(model);
329346
};
347+
330348
const debounceOptions = options?.debounce;
349+
331350
watch(
332351
modelRef,
333352
debounceOptions && debounceOptions.wait

0 commit comments

Comments
 (0)