gpt4 book ai didi

Angular form Validators.pattern does not work for matching 2 variants(角度形式验证器。模式不适用于匹配2个变体)

转载 作者:bug小助手 更新时间:2023-10-24 23:01:59 31 4
gpt4 key购买 nike



I have a unique case where I have to validate either datetime format or empty string. Either of those should be valid input. But for example malformed or incomplete datetime should fail validation.

我有一个独特的情况,我必须验证日期时间格式或空字符串。这两个选项中的任何一个都应该是有效输入。但是,例如,格式错误或不完整的DateTime应该无法通过验证。


   myForm = this.form.group({
...
ts: ['', [Validators.required, Validators.pattern('/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}|^(?=\s*$)$/')]],
});

Template:

模板:


       <input
type="datetime-local"
class="form-control"
formControlName="ts">

I checked my regex in https://regex101.com/ and it matches empty input or proper datetime format like 2023-09-14T17:17

我在https://regex101.com/中检查了我的正则表达式,它匹配空输入或正确的日期时间格式,如2023-09-14T17:17


However when in my app I leave the field empty, it still shows validation error.

然而,当我在我的应用程序中将该字段留空时,它仍然显示验证错误。


Can anyone recommend anything else I might be missing?

有谁能推荐我可能遗漏的其他东西吗?


Thank you in advance!

提前谢谢您!


更多回答

You can try to print out in HTML with {{ myForm.get('ts').errors | json }} and see what error you get.

您可以尝试使用{{myForm.get(‘ts’).errors|json}}以HTML格式打印输出,然后查看得到的错误。

优秀答案推荐

It's Validators.required that is returing an error on empty string not your Validators.pattern.

返回空字符串错误的是Validators.Required,而不是您的Validators.Pattern。



If your regex is matching empty string and that is acceptable then you can remove Validators.required.
You can write it like this:

如果您的正则表达式匹配空字符串,并且这是可以接受的,那么您可以删除Validators.Required。您可以这样写它:


 myForm = this.form.group({
...
ts: ['', [Validators.pattern('/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}|^(?=\s*$)$/')]],
});

Hope this helps!

希望这个能帮上忙!


更多回答

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com