繁体   English   中英

表单字段验证不起作用 Angular 8

[英]Form field validation not working Angular 8

我正在验证动态创建的表单字段。 我基本上有三个验证:

1. Value inputted should be between 0-10
2. Only numbers should be allowed
3. As the value is added greater than 10 it changes automatically to 10 but I want to show a message below the form field that it cannot be inputted above 10 and the submit button should be disabled. So it is invalid when when larger than 10 is added. 

在我的 HTML 中:

 <div class="form-group col-md-6" *ngFor="let p of data; let i = index">
        <label class="textfield_label">{{p.name}}</label>
        <div class="textfield" [class.has-error]="p.usageControl.invalid">
            <div *ngIf="p.usageControl.invalid">
            <input type="text" maxlength="2" min="0" max="10" (keypress)="isNumberKey($event)" (change)="limitUser($event)" class="form-control" id="p.name" name="p.name{{i}}" [(ngModel)]="p.usage" style="border: 2px red solid;" #p.usageControl="ngModel" required>
            <div class="alert alert-danger" style="margin-top: 5px;" *ngIf="p.usageControl.invalid">
               Please enter an number smaller than 10
               </div>
            </div>
            <input [hidden]="p.usageControl.invalid"  maxlength="2" min="0" max="10" (keypress)="isNumberKey($event)" (change)="limitUser($event)" type="text" class="form-control" id="p.name" #p.usageControl="ngModel" class="form-control" [(ngModel)]="p.usage" name="p.name{{i}}" required>
         </div>
      </div>

我也尝试过简单的:

  <input type="text" maxlength="2" min="0" max="10" (keypress)="isNumberKey($event)" (change)="limitUser($event)" class="form-control" id="p.name" name="p.name{{i}}" [(ngModel)]="p.usage"> 

在我的 typescript 我有两种方法:

isNumberKey(evt): boolean{
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
      return false;
    }
    return true;
  }
  limitUser(event){
    for (let i = 0; i < this.data.length; i ++) {
      if (this.data[i].usage < 0 || this.data[i].usage === null || this.data[i].usage === "") {
        this.data[i].usage  = 0;
      } if (this.data[i].usage > 10) {
        this.data[i].usage = 10;
      }
    }
  }

limitUser 限制用户输入任何高于 10 或低于 0 的值,因为它会按预期自动将其更改为 10 或 0。 isNumberOnly 确保用户只输入数字

对于模板驱动的表单,您可以像这样检查和修改值:

<input type="number"  [(ngModel)]="usage" min="0" max = "10" (ngModelChange)="usage > 10 ? usage = 10:true"/>

对于 Reactive 表单,您可以订阅输入的valueChanges ,如果超过 10,则以编程方式将其设置为 10。

试试这样:

.html

<input type="number" class="form-control" formControlName="usage" />

.ts

this.myForm = this.formBuilder.group({
  usage: [null, [Validators.min(0), Validators.max(10)]]
});

this.myForm.get("usage").valueChanges.subscribe(val => {
  if (val > 10) {
    this.myForm.get("usage").setValue(10);
  }
});

工作演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM