首页 > 解决方案 > 如何在按钮单击时验证输入不保存 0 或小于 0?

问题描述

我想通过角度 6 中的输入类型号保存 Length。但长度不应为 0 或小于 0 。当有人输入 0 或小于输入值时,它应该在按钮单击时显示错误。我尝试添加 min="1" 但它不起作用

<mat-form-field class="example-full-width">
                <input matInput type="number" [(ngModel)]="ItemModel.Length" placeholder="Length"  min="1"

                id="Length" name="Length" required>
              </mat-form-field>

标签: javascripthtmlangulartypescriptangular6

解决方案


You can set your min value to 0.1 and add ngclass for red border

    <mat-form-field class="example-full-width">
          <input matInput [(ngModel)]="ItemModel.Length" type="number" name="Length"
            placeholder="Length" [ngClass]="{ 'red': ItemModel.Length <= 0 && 
            greaterthenzero  }" min="0.1" required>
    </mat-form-field>

on submit button you can check your model value and add one boolean property and set to true if value is less than 0

    submit() {
         this.greaterthenzero = false;
         if (this.ItemModel.Length <= 0) {
             this.greaterthenzero = true;
         }
    }

推荐阅读