代码之家  ›  专栏  ›  技术社区  ›  Kajot

角度2限制输入字段

  •  -1
  • Kajot  · 技术社区  · 5 年前

    我想知道是否可以将一个输入字段限制为某种格式,例如,尽可能多的数字,然后是“.”,然后是2个数字?这基本上是对价格的投入…我不想像模式属性那样进行简单的验证。我希望用户不能做出错误的输入。

    2 回复  |  直到 5 年前
        1
  •  2
  •   Eliseo    5 年前

    你需要使用指令。在指令中,添加有关输入的热侦听器,并检查是否与指示的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\})?$'"
    

    (必须将\写为\,写为\,,写为\…)

        2
  •  1
  •   Ganz    5 年前

    您可以使用HTML5功能,regex输入

    使用regex模式验证:

    <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