表格使用async-validator检验composition
import Schema from 'async-validator'
import type { Rules, ValidateError, ValidateFieldsError } from 'async-validator'
export async function validateTable(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
}
import Schema from 'async-validator'
import type { Rules, ValidateError, ValidateFieldsError } from 'async-validator'
export async function validateTable(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
}
进一步封装错误消息
export function getValidateFieldsError(fields: ValidateFieldsError) {
const messages: string[] = []
Object.entries(fields).forEach(([key, value]) => {
messages.push(...value.map(item => item.message || ''))
})
return messages.filter(Boolean)
}
export function getValidateFieldsError(fields: ValidateFieldsError) {
const messages: string[] = []
Object.entries(fields).forEach(([key, value]) => {
messages.push(...value.map(item => item.message || ''))
})
return messages.filter(Boolean)
}