Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Form Validators - minLength & maxLength does not work on field type number

I am trying to develop a contact form, I want user to enter phone number values between length 10-12.

Notably same validation is working on Message field, Its only number field which is giving me trouble.

I found this answer but it is of no use for me.

I have code like following :

HTML :

<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
      <input type="number" formControlName="phone" placeholder="Phone Number">
      <input type="text" formControlName="message" placeholder="Message">
       <button class="button" type="submit" [disabled]="!myForm.valid">Submit</button>
</form>

TS :

this.myForm = this.formBuilder.group({
     phone: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(12)]],
     message: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(100)]]
});`
like image 903
Sangwin Gawande Avatar asked Sep 09 '17 10:09

Sangwin Gawande


3 Answers

Used it like following and worked perfectly :

phone: ['',  [Validators.required, Validators.min(10000000000), Validators.max(999999999999)]], 

customValidationService :

import { AbstractControl, ValidatorFn } from '@angular/forms';  export class customValidationService {    static checkLimit(min: number, max: number): ValidatorFn {     return (c: AbstractControl): { [key: string]: boolean } | null => {         if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {             return { 'range': true };         }         return null;     };   } } 
like image 169
Sangwin Gawande Avatar answered Sep 20 '22 14:09

Sangwin Gawande


try this working sample code :

component.html

<div class="container">
    <form [formGroup]="myForm" 
    (ngFormSubmit)="registerUser(myForm.value)" novalidate>
    <div class="form-group" [ngClass]="{'has-error':!myForm.controls['phone'].valid}">
        <label for="phone">Email</label>
        <input type="phone" formControlName="phone" placeholder="Enter Phone" 
        class="form-control">
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('minlength')">
            Your phone must be at least 5 characters long.
        </p>
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('maxlength')">
            Your phone cannot exceed 10 characters.
        </p>
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('required') && myForm.controls['phone'].dirty">
            phone is required
        </p>
    </div>
    <div class="form-group text-center">
        <button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>
    </div>
</form>
</div>

component.ts

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

export class AppComponent implements OnInit {
myForm: any;
constructor(
        private formBuilder: FormBuilder
    ) {}

ngOnInit() {
    this.myForm = this.formBuilder.group({
            phone: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
        });
}
}
like image 20
Chandru Avatar answered Sep 16 '22 14:09

Chandru


I have a trick that 100% work.

Define input of type 'text' and not 'number'.

For eg:

<input placeholder="OTP" formControlName="OtpUserInput" type="text">

Then use pattern which is part of Validation.

Like :

this.ValidOtpForm = this.formbuilder.group({
             OtpUserInput: new FormControl(
              { value:'', disabled: false },
          [
          Validators.required,
          Validators.minLength(6),
          Validators.pattern('[0-9]')
        ]),
});

It means we define input type text that is suitable for min length and we also define pattern(validation) for numeric value so that we can achieve both validation.

Remaining code :

<mat-error *ngIf="RegistrationForm.controls['Password'].hasError('minlength')">Use 6 or more characters with a mix of letters</mat-error>
<mat-error *ngIf="ValidOtpForm.controls['OtpUserInput'].hasError('pattern')">Please enter numeric value.</mat-error>
like image 34
nagender pratap chauhan Avatar answered Sep 19 '22 14:09

nagender pratap chauhan