fix(form): fix hasError called in FormModel.validate

This commit is contained in:
YuanHeDx 2025-03-17 21:14:54 +08:00 committed by YuanHeDx
parent b4450db944
commit 40eafff3ec
3 changed files with 25 additions and 8 deletions

View File

@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { hasError } from '../src/utils/validate';
import { FeedbackLevel, FieldError } from '../src/types';
describe('utils/validate', () => {
describe('hasError', () => {
it('should return false when errors is empty', () => {
expect(hasError({ xxx: [] })).toBe(false);
expect(hasError({ xxx: undefined })).toBe(false);
expect(hasError({})).toBe(false);
expect(hasError({ aaa: [], bbb: [] })).toBe(false);
expect(hasError({ aaa: undefined, bbb: [] })).toBe(false);
});
it('should return true when errors is not empty', () => {
const mockError: FieldError = { name: 'xxx', level: FeedbackLevel.Error, message: 'err' };
expect(hasError({ xxx: [mockError] })).toBe(true);
expect(hasError({ aaa: [mockError], bbb: [mockError] })).toBe(true);
expect(hasError({ aaa: undefined, bbb: [mockError] })).toBe(true);
});
});
});

View File

@ -279,6 +279,7 @@ export class FormModel<TValues = any> implements Disposable {
const warnings = feedbackToFieldErrorsOrWarnings<Warnings>(path, feedback);
if (field) {
debugger;
field.state.errors = errors;
field.state.warnings = warnings;
field.state.invalid = hasError(errors);

View File

@ -33,11 +33,5 @@ export function feedbackToFieldErrorsOrWarnings<T>(name: string, feedback?: Feed
} as T;
}
export const hasError = (errors: Errors) => {
for (let fieldErrors in errors) {
if (fieldErrors.length) {
return true;
}
}
return false;
};
export const hasError = (errors: Errors) =>
Object.keys(errors).some((key) => errors[key]?.length > 0);