我有这个验证器,可以验证值 id 数组。如下:
@Injectable()
@ValidatorConstraint({ async: true })
export class CustomValidator implements ValidatorConstraintInterface {
public constructor(
// to fetch the required fields
private readonly fieldsService: fieldsService,
// to fetch the provided values
private readonly valuesService: valuesService,
) {}
public async validate(
valuesIds: string[],
validationArguments: ValidationArguments,
): Promise<boolean> {
// first fetch the required fields
const requiredFields = await this.fieldsService.findRequired();
const fetches: Array<Promise<Values[]>> = []
for (let i = 0; i < valuesIds.length; i += 1) {
fetches.push(this.valuesService.findById(valuesIds[i]));
}
const values = Promise.all(fetches);
for (let i = 0; i < requiredFields.length; i += 1) {
// find the value with the corresponding field Id
const value = values.find(v => v.fieldId === requiredFields[i].id);
if (!value) {
// this is the issue I want to validate all fields instead of just one
// and I want to it to be formatted in the following fashion
// { fieldId: "corresponding error" }
throw new Error(`${requiredField.name} is required`);
}
return true;
}
}
我可以从验证函数返回 false,但问题是它只会是一个字段的一条消息,并且它将被分配给值字段而不是 fieldId。
试试这个:
import {
Injectable,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { ValidationError } from 'class-validator';
@Injectable()
@ValidatorConstraint({ async: true })
export class CustomValidator implements ValidatorConstraintInterface {
constructor(
private readonly fieldsService: FieldsService,
private readonly valuesService: ValuesService,
) {}
public async validate(
valuesIds: string[],
validationArguments: ValidationArguments,
): Promise<boolean | ValidationError[]> {
const requiredFields = await this.fieldsService.findRequired();
const values = await Promise.all(
valuesIds.map(id => this.valuesService.findById(id)),
);
let isValid = true;
const validationErrors: ValidationError[] = [];
requiredFields.forEach(field => {
const value = values.find(v => v.fieldId === field.id);
if (!value) {
isValid = false;
const error = new ValidationError();
error.property = field.id; // Use the field ID as the property
error.constraints = { isRequired: `${field.name} is required` };
validationErrors.push(error);
}
});
return isValid ? true : validationErrors;
}
}