typescript 角形材料:如何验证数字字段的最小值和最大值?

8ulbf1ek  于 2022-11-30  发布在  TypeScript
关注(0)|答案(5)|浏览(132)

我正在用Angular 8和Angular Material编写a small project
我有一个a number field,我想在其中指定最小值和最大值,但是我找不到任何关于如何在the matInput documentation中执行此操作的文档。

问题:matInput是否支持最小/最大验证?在Angular 材料中验证数字字段的最佳方式是什么?

到目前为止,我尝试了标准的html5最小和最大属性,不幸的是,验证引擎没有捕捉到这些属性。我还尝试了一些来自互联网的例子,这些例子在Angular 8中不起作用。

6kkfgxo0

6kkfgxo01#

为了验证matInput的内容,可以将其 Package 在mat-form-field中,如下所示:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput [formControl]="numberFormControl">
    <mat-error *ngIf="numberFormControl.hasError('min')">
      The value is lower than the minimum
    </mat-error>
    <mat-error *ngIf="numberFormControl.hasError('max')">
      The value is greater than the maximum
    </mat-error>
  </mat-form-field>
</form>

并对验证器使用表单控件:

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'input-errors-example',
  templateUrl: 'input-errors-example.html',
  styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {
  numberFormControl = new FormControl('', [
     Validators.min(3),
     Validators.max(6),
  ]);
}

这适用于最小值和最大值,您可以以相同的方式使用minlength和maxlength验证器,文档如下:
https://angular.io/api/forms/Validators

wqnecbli

wqnecbli2#

我建议您使用React式表单,因为它将使您的业务逻辑留在ts代码中,使您的模板更容易阅读和维护。

sampleForm = new FormGroup({}) // Instantiating our form

constructor(private fb: FormBuilder){ // Injecting the ReactiveForms FormBuilder.
 this.sampleForm = fb.group({
    // Adding the "age" input to our FormGroup along with its min-max Validators.
    'age': ['', [Validators.min(5), Validators.max(10)]] 
  })
}

还有你的html

<form [formGroup]="sampleForm ">
<label for="age">Age</label>
  <!-- formControlName will bind the age field declared in the ts code. -->
  <input type='number' id="age" formControlName="age">
</form>
8yoxcaq7

8yoxcaq73#

你可以使用React式的方法来创建表单。这些在第一次的时候可能看起来很可怕,但是最终在设置不同的验证器时会非常有帮助。
步骤1:导入依赖关系

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
   imports: [
   // other imports ...
   ReactiveFormsModule
   ],
})
export class AppModule { }

步骤2:创建新的FormObject

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
  });
}

步骤3:创建模板

<form [formGroup]="profileForm">

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>

</form>

步骤4:添加验证器

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: ['', Validators.required, Validators.min(3)],
    lastName: ['', Validators.required, Validators.min(3)]
  });
}
jslywgbw

jslywgbw4#

默认情况下,Angular 模板驱动的表单无法验证最小和最大HTML5验证-这是一个框架问题。您可以编写一个指令来解决这个问题,或者更简单的解决方案是在提交时验证表单。
我所陈述的问题可以在这里看到和测试https://stackblitz.com/edit/angular-input-min-max?file=src/app/app.component.html
有几个指令可用,一个我能够找到,但它也有一些问题。自己试试
https://www.concretepage.com/angular-2/angular-4-min-max-validation#Template-driven
另一种可能的简洁方法是在代码中使用React式表单而不是模板驱动的表单:)

5uzkadbs

5uzkadbs5#

试试看:
minlengthmaxlength
但类型不应是数字,例如:

<input matInput placeholder="Test" minlength="3" maxlength="3">

Demo

相关问题