使用`class-validator`在打字稿中确认密码 [英] Password confirmation in TypeScript with `class-validator`
本文介绍了使用`class-validator`在打字稿中确认密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天,我想弄清楚如何在应用程序的后端(NestJS)验证注册表单。我只是想知道是否存在一种方法来验证password
和passwordConfirm
匹配,使用class-validator
包来构建自定义验证器或利用提供的验证器。我考虑的是类验证器,而不是字段验证器。
// Maybe validator here
export class SignUpDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;
@IsString()
@MinLength(4)
@MaxLength(20)
@Matches(/((?=.*d)|(?=.*W+))(?![.
])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})
password: string;
@IsString()
@MinLength(4)
@MaxLength(20)
passwordConfirm: string;
}
您有什么建议?
推荐答案
最终我设法解决了密码匹配问题,这要归功于我的问题评论中@ChristopheGeers的建议:
@Piero:前面提到的目前还不支持。但是这里有一个装饰符示例(@IsLongerThan):LINK.它检查一个属性是否比另一个属性长。因此,可以将一种属性与另一种属性进行比较。您可以使用此示例创建一个可以执行您想要的操作的装饰器。
这里是我提出的解决方案:
sign-up.dto.ts
export class SignUpDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;
@IsString()
@MinLength(4)
@MaxLength(20)
@Matches(/((?=.*d)|(?=.*W+))(?![.
])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})
password: string;
@IsString()
@MinLength(4)
@MaxLength(20)
@Match('password')
passwordConfirm: string;
}
match.decator.ts
import {registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';
export function Match(property: string, validationOptions?: ValidationOptions) {
return (object: any, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [property],
validator: MatchConstraint,
});
};
}
@ValidatorConstraint({name: 'Match'})
export class MatchConstraint implements ValidatorConstraintInterface {
validate(value: any, args: ValidationArguments) {
const [relatedPropertyName] = args.constraints;
const relatedValue = (args.object as any)[relatedPropertyName];
return value === relatedValue;
}
}
这篇关于使用`class-validator`在打字稿中确认密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文