Angular 角度7输入编号验证

Angular 角度7输入编号验证,angular,Angular,在angularjs中: <form name="f" novalidate> <input type="number" ng-model="x" name="x"> </form> <div ng-if="f.x.$error.number">NaN</div> 我喜欢使用FormGroup和FormBuilder验证我的表单 Angular 7 HTML: <form [formGroup]="myFormGroup"&g

在angularjs中:

<form name="f" novalidate>
<input type="number" ng-model="x" name="x">
</form>

<div ng-if="f.x.$error.number">NaN</div>

我喜欢使用FormGroup和FormBuilder验证我的表单

Angular 7 HTML:

<form [formGroup]="myFormGroup">
  <input type="number" ng-model="x" name="x" 
   formControlName="myInputField">
</form>

因此,它立即验证。我希望我能帮上忙。

您可以通过添加Angular

有一个现有的用于所需的:

您可以使用模式并传递正则表达式来检查数值:/^[a-zA-Z0-9]+$/

然后通过将输入声明为FormControl来添加对输入的引用,添加验证器并在输入的FormControl属性中传递引用。别忘了在表单组中添加新创建的表单控件

添加到类:

let numericRegex = /^[a-zA-Z0-9]+$/;
let myNumeric = new FormControl('', [
  Validators.required,
  Validators.pattern(numericRegex), // <-- Here's how you pass in the custom validator using regex.
]);
让numericRegex=/^[a-zA-Z0-9]+$/;
让myNumeric=newFormControl(“”[
需要验证器,

验证程序模式(numericRegex),//我在某些地方不需要必填项-我想允许空白,但不允许非数字,我想保留输入类型number,这样模式就不起作用了。顺便说一句,您的模式是错误的……所以,您只需要数字和空白?有什么具体说明为什么或在哪里使用此验证吗?是针对电话号码还是其他什么?我希望这里有最大的通用性--e.g.有些地方允许空值,有些地方不需要空值。有些地方我不需要必填-我想允许空白,但不需要非数字,我想保留输入类型数字,所以模式不起作用。顺便说一句,你的模式也错了…如果你想允许空白,你只需要删除
验证程序。必填
,因为所有验证程序都在同一个位置数组。你为什么这么急着要保留输入类型号?你在我的模式中哪里发现了错误?让我知道。我希望我们能得到你想要的结果..1.1.1e1都是有效的数字
public myFormGroup: FormGroup;
constructor(private formBuilder: FormBuilder, ...) {
  this.myFormGroup = this.formBuilder.group({
    myInputField: ['', [Validators.required, 
    Validators.pattern('^\\d*$')]]
  });
}
let numericRegex = /^[a-zA-Z0-9]+$/;
let myNumeric = new FormControl('', [
  Validators.required,
  Validators.pattern(numericRegex), // <-- Here's how you pass in the custom validator using regex.
]);
<input class="form-control"
      [formControl]="myNumeric" required >

  <div *ngIf="myNumeric.errors.required">
    value is required.
  </div>
  <div *ngIf="myNumeric.errors.pattern">
    only alphanumeric
  </div>