Alaa'
Alaa'

Reputation: 487

Validation of input type number in Angular 6

I'm working in Angular 6, I have this input in 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>

now the input allows to enter such values:

9....5

6.7.8.4

0-794++++1--3

8eeee.eeeee

I need to check the validation of this number plus the maxlength = 10

I tried many things for number validation like:

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

nothing worked

Also for the maxlength, I tried many things, nothing did work, some are:

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

Edit: Solved I found the solution from these 2 links 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;

      }

And in html file:

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

Upvotes: 0

Views: 861

Answers (1)

Severin Klug
Severin Klug

Reputation: 754

You can use Angular Reactive Forms and add validators to your controls.

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

After this, you can simply ask for myControl.valid

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

For your isNumber valitation you can write your own custom validator.

Upvotes: 2

Related Questions