验证Angular 6中的输入类型编号

时间:2019-05-13 12:51:27

标签: html angular validation

我在Angular 6中工作,我在ngForm中有此输入

    <form #editForm="ngForm" id="editForm" class="well-model-form px-2">
.
.
.
  <div class="col-4">
<input type="number" class="input-style-text"
 [(ngModel)]="myModeldata.depth.value" name="depth">
</div>

.
.
</form>

现在输入允许输入这些值:

9 .... 5

6.7.8.4

0-794 ++++ 1--3

8eeee.eeeee

我需要检查此数字的有效性以及maxlength = 10

我尝试了很多用于数字验证的事情,例如:

    <input type="number" class="input-style-text"
     [(ngModel)]="myModeldata.depth.value" name="depth"
[ngClass]="{ 'is-invalid': depth?.touched && depth?.invalid }"

div *ngIf="depth?.invalid && (depth?.dirty || depth?.touched)"
       class="alert alert-danger">
  </div>
or 
div *ngIf="editForm.depth?.invalid && (editForm.depth?.dirty || editForm.depth?.touched)"
       class="alert alert-danger">
  </div>

and in css
input.form-control.ng-touched.ng-dirty.ng-invalid,
input.form-control.is-invalid {
  border: 1px solid #f86c6b !important;
}

没有任何作用

对于最大长度,我尝试了很多事情,但没有任何效果,

<input... ngModel maxlength="10" required>

<div *ngIf="editForm.depth?.maxlength">
   Depth can be max 10 characters long.
</div>

or
<input ng-maxlength="10" #undepth>
<div *ngIf="undepth?.maxlength">
   Depth can be max 10 characters long.
</div>

编辑:已解决 我从这两个链接中找到了解决方案 inputTypeNumber inputAcceptNumbersOnly

  keyPress(event: any, value: string) {
        const pattern = /^[0-9\+\-\.]{1,9}$/;

        let inputChar = String.fromCharCode(event.charCode);

        if (value.toString().length == 10)
          event.preventDefault();

        if (event.keyCode != 8 && !pattern.test(inputChar))
          event.preventDefault();

        if (event.charCode == 46 && value.indexOf('.') >= 0)//has one dot
          event.preventDefault();

        if ((event.charCode == 43 || event.charCode == 45) && value.toString().length >= 1) //+ or - only comes in the first
          event.preventDefault();

        return null;

      }

在html文件中:

<input type="text" class="input-style-text" [(ngModel)]="myModeldata.depth.value"
                                    name="depth"
                                       (keypress)="keyPress($event, myModeldata.depth.value)">

1 个答案:

答案 0 :(得分:2)

您可以使用Angular Reactive Forms并将验证器添加到控件中。

https://angular.io/guide/reactive-forms#simple-form-validation

此后,您只需索取myControl.valid

editForm = this.fb.group({
  myModeldata: ['', Validators.maxLength(10)],
});

对于isNumber验证,您可以编写自己的自定义验证器。