我正在验证动态创建的表单字段。我基本上有三个验证:
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">
在我的打字稿中,我有两种方法:
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 确保用户只输入数字