Angular 2限制输入字段

时间:2019-01-31 12:44:51

标签: angular input restriction

我想知道是否可以将输入字段限制为某种格式,例如,任意数量的数字,然后按“。”。然后是2位数?这基本上是价格的输入...而且我不希望像pattern属性这样的简单验证。我希望用户不能做出错误的输入。

2 个答案:

答案 0 :(得分:2)

您需要使用指令。在指令中添加有关输入的hotListener,并检查是否与指定的regExpr匹配。 我前段时间做了指令屏蔽。 the stackblitz中的指令,带有广告的含义,即该代码按“原样”提供,没有任何形式的保证。

@Directive({
  selector: '[mask]'
})
export class MaskDirective {
  @Input()
  set mask(value) {
    this.regExpr = new RegExp(value);
  }

  private _oldvalue: string = "";
  private regExpr: any;
  private control: NgControl;
  constructor(injector: Injector) {
    //this make sure that not error if not applied to a NgControl
    try {
      this.control = injector.get(NgControl)
    }
    catch (e) {
    }
  }
  @HostListener('input', ['$event'])
  change($event) {

    let item = $event.target
    let value = item.value;
    let pos = item.selectionStart; //get the position of the cursor
    let matchvalue = value;
    let noMatch: boolean = (value && !(this.regExpr.test(matchvalue)));
    if (noMatch) {
      item.selectionStart = item.selectionEnd = pos - 1;
      if (item.value.length < this._oldvalue.length && pos == 0)
        pos = 2;
      if (this.control)
        this.control.control.setValue(this._oldvalue, { emit: false });

      item.value = this._oldvalue;
      item.selectionStart = item.selectionEnd = pos - 1; //recover the position
    }
    else
      this._oldvalue = value;
  }
}

当您在字符串(或html)中写“ mask”时要小心。例如对于一个数字宽度为两位小数的数字是:

[mask]="'^[+-]?([1-9]\\d*|0)?(\\.\\d\{0,2\})?$'"

(\必须写为\\,{写为\ {,}写为\} ...)

答案 1 :(得分:1)

您可以使用HTML5功能,正则表达式输入

使用正则表达式模式验证:

<input type="text" name="weight" value="" pattern="^[1-9]\d{0,*}\.\d{2}$" />

您还可以使用此库,并使用键修饰输入:

<input type="text" pattern="[0-9]+" ng-pattern-restrict /> 

回购:github.com/AlphaGit/ng-pattern-restrict

相关问题