如何在单击按钮时验证输入不保存 0 或小于 0?

How to validate Input from not saving 0 or less then 0 on button click?

我想通过 angular6 中的输入类型编号来保存长度。但长度不应为 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>

选项 1:

你可以在按钮点击事件上检查这个

if (this.form.value.controlName <= 0) {
    alert("Please enter value greater then 0");        
    return false;
  }

选项 2:

controlName: ['', [Validators.required, Validators.minLength(0)]]

在HTML

<span *ngIf="f.controlName.errors && f.controlName.hasError('minlength') && f.controlName.touched" class="error-msg">
    {{YOUR MESSAGE}}</span>

TS文件中

get f() { return this.form.controls; }

尝试在您的输入框中添加 oninput="this.value = Math.abs(this.value)==0?1: Math.abs(this.value)" 以避免输入 0 或负数

<input matInput type="number" [(ngModel)]="modelName" placeholder="Length"  
min="1" id="Length" name="Length"  oninput="this.value = 
Math.abs(this.value)==0?1: Math.abs(this.value)" required />

Demo


输入错误的值后尝试此操作以手动删除文本框中的值,

<input matInput type="number" [(ngModel)]="modelName" placeholder="Length"  min="1" id="Length" name="Length" (change)="valueChange($event)" required>

在组件中

valueChange(event) {
    if (event.target.value <= 0) {
     this.modelName = '';
      return false;
    }

Demo

您必须添加一个带有错误样式的 span 元素,例如最初隐藏的红色文本,当调用按钮函数时检查该值的值是否存在,如果不存在则显示 span,然后将其隐藏

默认情况下不会抛出任何错误。

如果您想默认抛出错误,请尝试通过添加模式属性来使用这样的模式匹配

pattern="^+?[1-9]\d*$"。 在输入.

您可以将最小值设置为 0.1 并为红色边框添加 ngclass

    <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>

在提交按钮上,您可以检查您的模型值并添加一个布尔值 属性 并在值小于 0 时设置为 true

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