我想要以下dto:
export class SetEntryPasswordDto {
@ApiProperty()
@Validate(EntryBelongsToUser)
@Validate(EntryIsNotLocked)
@Type(() => Number)
@IsNumber()
id: number;
@ApiProperty()
@IsString()
@IsNotEmpty()
@Validate(PasswordMatchValidator)
@Matches(EValidator.PASSWORD, { message: 'password is not strong enough' })
password: string;
@ApiProperty()
@IsNotEmpty()
@IsString()
confirmPassword: string;
@ApiProperty()
@IsOptional()
@IsString()
passwordHint?: string;
@IsNumber()
userId: number;
}它的问题是,我需要做一些异步验证,我想使用类验证器lib来完成这项工作。
我的问题是:如果我像上面的代码片段一样这样做,我能确定第一个完成的代码是EntryIsNotLocked吗?如果没有,那么如何让这些验证按顺序执行呢?
谢谢。
其他信息:
似乎有一些信息很重要。
EntryBelongsToUser和EntryIsNotLocked是ValidatorConstraint类。例如,其中之一看起来如下所示:
@ValidatorConstraint({ name: 'EntryIsNotLocked', async: false })
@Injectable()
export class EntryIsNotLocked implements ValidatorConstraintInterface {
constructor(
private readonly entryService: EntryService,
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
// here goes some validation logic
}
public defaultMessage(args: ValidationArguments): string {
return `Unauthorized to execute this action`;
}
}第二个看起来完全一样。所以问题是,我是否可以通过将ValidatorConstraint装饰器的async选项设置为false来保证它们的顺序?
发布于 2020-08-07 22:56:10
不,你不能确定异步函数的顺序。这就是在类验证器包中使用validateSync方法的原因。您可以使用validateSync方法代替常规的validate方法来执行简单的非异步验证。
有关参考,请参阅this。
https://stackoverflow.com/questions/63290873
复制相似问题