表格使用async-validator检验composition
# 表格使用async-validator检验composition
import Schema from 'async-validator';
import type { Rules, ValidateFieldsError, ValidateError } from 'async-validator';
export const validateTable = async (table: Record<string, unknown>[], rules: Rules) => {
const validator = new Schema(rules);
let error: {
errors: ValidateError[],
fields: ValidateFieldsError,
} | undefined;
await Promise.all(table.map((item) => validator.validate(item))).catch((e) => {
error = e;
});
if (error) {
throw error;
}
return true;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 进一步封装错误消息
export const getValidateFieldsError = (fields: ValidateFieldsError) => {
const messages: string[] = [];
Object.entries(fields).forEach(([key, value]) => {
messages.push(...value.map((item) => item.message || ''));
});
return messages.filter(Boolean);
};
1
2
3
4
5
6
7
2
3
4
5
6
7
上次更新: 2023/06/01, 12:40:50