输入上的 Angular2 模式验证器

Angular2 pattern validator on Input

我正在尝试使用以下正则表达式设置模式验证器:

Try Regex here

这应该允许我得到 1 到 3 位数字,然后是最多 2 位数字的小数部分,并且也应该允许空值。

问题是我的输入是 text 类型并且验证器拒绝了我的输入(任何输入,因为我相信它不被视为数字);或者输入的类型是 number 并且没有 step="any" 如果我有十进制输入(而正则表达式似乎正在处理更简单的值)并且使用 step="any" 我的输入值将被拒绝似乎我的正则表达式根本不起作用,因为 step.

允许任何值
<form (ngSubmit)="onSubmit()" #bottleUpdatePriceForm="ngForm" >

    <div class="form-group" *ngFor="let bottle of bottleArrayToUpdate; let i = index">
      <label for="bottlePrice">{{bottle.name}} : </label>
      <input type="number" class="form-control" name="bottlePrice" autocomplete="off" step="any"
      [pattern]="pricePattern"
      [(ngModel)]="bottleArrayToUpdate[i].price">
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
    <!--(click)="bottleUpdatePriceForm.reset();"-->
</form>

编辑: 为正则表达式绑定添加我的组件代码

private pricePattern = /^(((0|[1-9]\d{0,2})(\.\d{2})?)|())$/;

我真的不在乎是文本还是数字,我只需要模式来处理我的输入...任何见解或我缺少的东西?

这是一个 plunkr 中的工作示例:https://plnkr.co/edit/znVaS7?p=info

您可以在 plunkr 中切换输入行以查看不同的情况:

<input type="text" class="form-control" name="bottlePrice" autocomplete="off"

<input type="number" class="form-control" name="bottlePrice" autocomplete="off" step="any"


与主要问题无关:有没有什么方法可以从组件而不是直接在模板中调用表单重置? ==> bottleUpdatePriceForm.reset();

我在想,这只是为了奖金。

非常感谢

这不是无法正常工作的正则表达式的直接解决方案,但它具有相同的目的。因此,删除模式,只需使用 maxmin 更改您的输入:

<input type="number" class="form-control" name="bottlePrice" 
     autocomplete="off" step="any" max="999" min="0"
     [(ngModel)]="bottleArrayToUpdate[i].price">