如何在ionic3中使用最小/最大比较验证来验证2个字段?

时间:2018-12-28 14:17:25

标签: sass ionic3 angular6

正在处理包含2个字段(如min和max)的反应形式组,数据来自硬编码数组data。当我们在相应字段中输入值时,只想显示验证值,即最小值应大于最大值

1 个答案:

答案 0 :(得分:0)

希望这对您有帮助

创建如下表格

createForm() {
    this.personalDataForm = new FormGroup({
      fieldOne: new FormControl("", [Validators.minLength(5), Validators.maxLength(15)])
// ...
    });
  }

向模板添加验证

<form [formGroup]="personalDataForm">
  <ion-row>
   <label class="lbl-lnu">fieldOne :</label>
   <input type="text" class="input-lnu" formControlName="fieldOne">
   <div class="form-control-feedback" *ngIf="personalDataForm.controls.fieldOne.errors && (personalDataForm.controls.fieldOne.dirty || personalDataForm.controls.fieldOne.touched)">
      <p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.minlength">Minimum length is 5</p>
      <p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.maxlength">Maximun length is 15</p>
   </div>
   </div>
 </ion-row>
</form>

要在提交时进行验证,请使用波纹管功能

function isValid(): boolean {
  const valid = this.personalDataForm.valid
  if (!valid) { // if not valid fire validation
    Object.keys(this.personalDataForm.controls).forEach(field => {
        const control = this.personalDataForm.get(field);
        control.markAsTouched({ onlySelf: true });
      });
  }
  return valid; // if form data valid return true, otherwise false
}