javascript - 如何处理 ngFor 中输入类型的动态正则表达式值?

标签 javascript regex angular typescript

我有一个对象数组,每个对象都有必须动态生成的输入字段的详细信息,我已经根据从 API 接收到的类型完成了动态输入字段生成,但我无法匹配正则表达式。

 <ng-container *ngFor="let list of inputList">
    <label>{{list.key}}</label>
    <input [type]="list.type" [value]="list.value" [required]="list.required" [pattern]="list.regex"  (input)="valueChange($event)"  />
    </ng-container>

API 响应输入列表

[{key: "Name", type: "text", value: "", required: true, mandatory: false, regex: [A-Z][a-z]$}
{key: "Number", type: "number", value: "", required: true, mandatory: false, regex: [0-9]{10}$}
{key: "description", type: "textarea", value: "", required: true, mandatory: false, regex: [a-z]{10,250}}
{key: "email", type: "text", value: "", required: true, mandatory: false, regex: /\S+@\S+\.\S+/}];

但是该模式不起作用是否有任何替代方案只能接受来自键盘的这些输入,例如在移动用户不应该能够键入除数字之外的其他键的情况下。

最佳答案

如果您将正则表达式作为字符串传递并且不包括 /,它应该可以工作,如下所示:

[{key: "Name", type: "text", value: "", required: true, mandatory: false, regex: "[A-Z][a-z]$"}
{key: "Number", type: "number", value: "", required: true, mandatory: false, regex: "[0-9]{10}$"}
{key: "description", type: "textarea", value: "", required: true, mandatory: false, regex: "[a-z]{10,250}"}
{key: "email", type: "text", value: "", required: true, mandatory: false, regex: "\S+@\S+\.\S+"}]

<form onsubmit="return false;">
  <input type="text" pattern="[A-Z][a-z]$">
  <input type="submit">
</form>

另一方面,您确定这些是您要验证这些字段的正则表达式吗?

[A-Z][a-z]$ - 一个大写字母和一个小写字母,正好是这两个字母。也许您的意思是 [A-Z][a-z]+(一个大写字母,任意数量的小写字母)。

[0-9]{10}$ - 恰好十位数。

[a-z]{10,250} - 10 到 250 个小写字母,没有空格或点。

\S+@\S+\.\S+ - 对于电子邮件验证,有很好的示例和深入的讨论 here .

关于javascript - 如何处理 ngFor 中输入类型的动态正则表达式值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64011477/

相关文章:

javascript - 在 IE11 上运行 Angular 5 应用程序时参数无效

javascript - :after element gives wrong value for event. toElement.clientWidth 上的 Angular MouseEvent

javascript - 如何在传单中显示/隐藏带标记的折线

javascript - Angular:* ngFor在数组更改后不更新 View

java - 使用正则表达式查找字符串中的重复字符

regex - 如何系统地替换大量文本中 mustache 标签内的文本?

Java - 异常处理 - 正则表达式 - 匹配方法不适用于扫描仪输入

css - 在 Angular 2 中使用 md-grid-list 进行响应式设计

javascript - parseInt vs unary plus,什么时候用哪个?

validation - Angular 2 路由参数验证