Javascript 可以使用CustomValidator防止数据输入文本框吗?

Javascript 可以使用CustomValidator防止数据输入文本框吗?,javascript,angular,typescript,Javascript,Angular,Typescript,我已将以下代码添加到我的角度组件中: NumberValidator(event,element) { if (this.onlyNumberKey(event) == false) return false; if (this.maxLength(event) == false) return false; else return true; } maxLength(event) { var test = even

我已将以下代码添加到我的角度组件中:

NumberValidator(event,element) {
    if (this.onlyNumberKey(event) == false)
      return false;
    if (this.maxLength(event) == false)
      return false;
    else
      return true;

  }

  maxLength(event) {
    var test = event.target.value;
    if (event.target.value.length + 1 > 2)
      return false;
    else
      return true;
  }

  onlyNumberKey(event) {
    let charCode = (event.query) ? event.query : event.keyCode;
    console.log(charCode);
    if (charCode > 31
      && (charCode < 48 || charCode > 57))
      return false;

    return true;
  }
NumberValidator(事件,元素){
if(this.onlyNumberKey(event)==false)
返回false;
if(this.maxLength(事件)==false)
返回false;
其他的
返回true;
}
最大长度(事件){
var测试=event.target.value;
如果(event.target.value.length+1>2)
返回false;
其他的
返回true;
}
onlyNumberKey(事件){
让charCode=(event.query)?event.query:event.keyCode;
console.log(charCode);
如果(字符代码>31
&&(字符编码<48 | |字符编码>57))
返回false;
返回true;
}
和我的html:

<input type="text" (keypress)="firstNameValidator($event, this)" formControlName="firstName" required>

有没有一种更优雅的方法可以使用角度反应形式来实现这一点,因为我觉得这有点像黑客。我已经研究过CustomValidator,但是,它们似乎只是告诉您是否存在验证错误,即,如果出现验证错误,它们似乎不会停止向文本框输入数据。

您可以使用Angular中的属性,它将在
EventEmitter
的帮助下,监听输入的
keydown
事件:

HTML代码:

Enter numbers:
<input type="text" [(ngModel)]="value" onlyNumbersWithMax (onMaxValueReached)='onMaxValueReached_Client($event)'/>
<br/>
<div *ngIf="warningMessage">{{warningMessage}}</div>
指令.TS代码:

import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from "@angular/core";

@Directive({
  selector: "input[onlyNumbersWithMax]"
})

export class NumberDirective {
  @Output() onMaxValueReached = new EventEmitter();
  maxValue: number = 2; // Set the max value here for input values

  constructor(private _el: ElementRef) { }

  @HostListener("keydown", ["$event"]) onInputChange(event) {
    const initalValue = this._el.nativeElement.value; // Get the initial value
    this.onMaxValueReached.emit(undefined);  // Reset the error
    let charCode = event.query ? event.query : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) &&
      this._el.nativeElement.value == ""
    ) {
      // This code block is just a work around to reset the character or invalid value as we are using keydown event so the flow of control is just moving before setting empty value
      var that = this;
      setTimeout(function () {
        that._el.nativeElement.value = "";
      }, 10);
      event.stopPropagation();
    } else {
      if (initalValue.length >= this.maxValue && charCode != 8) {
        event.preventDefault();
        this.onMaxValueReached.emit(
          "The max value for an input is " + this.maxValue
        );
      }
    }
  }
}
import{Directive,ElementRef,HostListener,Input,Output,EventEmitter}来自“@angular/core”;
@指示({
选择器:“输入[onlyNumbersWithMax]”
})
导出类编号指示{
@Output()onMaxValueReach=新的EventEmitter();
maxValue:number=2;//在此处设置输入值的最大值
构造函数(私有_el:ElementRef){}
@HostListener(“keydown”,[“$event”])onInputChange(事件){
const initalValue=this.\u el.nativeElement.value;//获取初始值
this.onMaxValueReach.emit(未定义);//重置错误
让charCode=event.query?event.query:event.keyCode;
如果(字符码>31&(字符码<48 | |字符码>57)&&
这是。_el.nativeElement.value==“”
) {
//这个代码块只是重置字符或无效值的一个变通方法,因为我们使用的是keydown事件,所以控制流在设置空值之前只是移动
var=这个;
setTimeout(函数(){
那._el.nativeElement.value=“”;
}, 10);
event.stopPropagation();
}否则{
if(initalValue.length>=this.maxValue&&charCode!=8){
event.preventDefault();
此.onMaxValueReach.emit(
“输入的最大值为”+this.maxValue
);
}
}
}
}

实现这一目标的最佳方法是制定自定义指令

自定义指令可以监听您使用HostListener定义的任何事件,例如keyup/keydown


您可以在此指令中定义验证,并将其应用于文本字段。

为什么不将输入类型更改为“数字”?@Mark S,maxLength函数仍然需要一个数字。或者它会吗?有很多是内置在角度上的,当涉及到反应形式时,它们可以是单独的,也可以是组合的。这些对你不起作用?R.Richard's,据我所知,如果发生错误,它们不允许你停止数据输入-它们似乎只在数据输入错误发生时警告你并阻止提交?我可能错了though@w0051977使用数字输入类型,您可以指定该字段中允许的“max”和“min”值抱歉,这根本不起作用。我已在Visual Studio 2017中尝试了您的代码,但它不允许我在文本框中输入任何内容。@w0051977您可以检查日志值的详细信息,然后检查它的去向wrong@w0051977或者你可以分享stackblitz,在那里我可以重现一个问题你的代码只将第一个字符限制为一个数字-第二个字符可以是任何东西例如,可以输入:1a、2b、5f等。在我将答案标记为已接受之前,您是否能够回答我上述评论中有关断点的问题?谢谢
import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from "@angular/core";

@Directive({
  selector: "input[onlyNumbersWithMax]"
})

export class NumberDirective {
  @Output() onMaxValueReached = new EventEmitter();
  maxValue: number = 2; // Set the max value here for input values

  constructor(private _el: ElementRef) { }

  @HostListener("keydown", ["$event"]) onInputChange(event) {
    const initalValue = this._el.nativeElement.value; // Get the initial value
    this.onMaxValueReached.emit(undefined);  // Reset the error
    let charCode = event.query ? event.query : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) &&
      this._el.nativeElement.value == ""
    ) {
      // This code block is just a work around to reset the character or invalid value as we are using keydown event so the flow of control is just moving before setting empty value
      var that = this;
      setTimeout(function () {
        that._el.nativeElement.value = "";
      }, 10);
      event.stopPropagation();
    } else {
      if (initalValue.length >= this.maxValue && charCode != 8) {
        event.preventDefault();
        this.onMaxValueReached.emit(
          "The max value for an input is " + this.maxValue
        );
      }
    }
  }
}