【发布时间】:2021-06-30 12:20:23
【问题描述】:
我正在学习nestjs作为我的工作要求
这是我的正则表达式:/(?=[^\d].*)^[\w]{4,}$/,这意味着第一个字符不能是数字,整个字符串至少 4 个字符
这里是 DTO:
import { IsString, IsPhoneNumber, Matches } from 'class-validator';
export class CreateUserDto {
@Matches(/(?=[^\d].*)^[\w]{4,}$/, {
message:
'the first character of the username must not be a number. Username must contains at least 4 characters',
})
username: string;
@IsString()
password: string;
@IsPhoneNumber('VN')
phoneNumber: string;
}
无论请求正文中的用户名是什么,它仍然通过,即使是一个空字符串 但是当我为用户名字段发布一个普通数字时,服务器响应了一个错误作为匹配装饰器的默认操作
{
"statusCode": 400,
"message": [
"username must be a string"
],
"error": "Bad Request"
}
我还在 main.ts 中启用了验证
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
app.useGlobalPipes(new ValidationPipe());
await app.listen(9000);
}
bootstrap();
谁能帮我解释一下?感谢您的帮助
【问题讨论】:
-
您的意思是至少四个字符而不是单词?
-
另外,不仅匹配的字符串不能是数字。它也不能以数字开头,例如
333jjj将不匹配。 -
究竟是什么问题?
-
以前,我无法使用 Matches 装饰器通过正则表达式验证用户名字段。但在删除
dist文件夹后。它就像一个魅力。实际上,我刚刚解决了我的问题。无论如何,感谢您的关注:) -
哦,是的,我的意思是“字符”。这是我的拼写错误
标签: typescript nestjs class-validator