web-dev-qa-db-fra.com

Angular 4 Validateurs de formulaire - minLength & maxLength ne fonctionne pas sur le numéro de type de champ

J'essaie de développer un formulaire de contact, je veux que l'utilisateur entre les valeurs de numéro de téléphone d'une longueur comprise entre 10 et 12.

Notamment, la même validation fonctionne sur le champ Message , son seul champ qui me donne des ennuis.

J'ai trouvé cette réponse mais elle ne me sert à rien.

J'ai un code comme suit:

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)]]
});`
28
Sangwin Gawande

Mise à jour 1:

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

Utilisé comme suit et a parfaitement fonctionné:

 phone: ['',  [Validators.required, customValidationService.checkLimit(10000000000,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;
    };
  }
}
12
Sangwin Gawande

essayez cet exemple de code de travail:

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

composant.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)])]
        });
}
}
7
Chandru

J'ai un truc qui fonctionne à 100%.

Définit une entrée de type 'text' et non 'number'.

Pour par exemple:

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

Ensuite, utilisez le modèle qui fait partie de la validation.

Comme :

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

Cela signifie que nous définissons un texte de type entrée adapté à la longueur minimale et que nous définissons également un modèle (validation) pour une valeur numérique, de manière à pouvoir réaliser la validation.

Code restant:

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

Vous ne devez pas utiliser la longueur ici, pour min et max, utilisez un validateur personnalisé comme celui-ci,

_var numberControl = new FormControl("", CustomValidators.number({min: 10000000000, max: 999999999999 }))
_

Angular2 min/max validators

3
Sajeetharan - MSFT

Si vous voulez valider un champ par plusieurs validateurs, vous devriez essayer ceci

phone: ['', Validators.compose([
        Validators.required, 
        Validators.minLength(10),
        Validators.maxLength(12)])
      ])],
0
Prachi Shah

Conservez <input type="number" /> et transformez simplement les valeurs int en chaînes.

const phoneControl: FormControl = this.myForm.controls.phone;

// Do not forget to unsubscribe

phoneControl.valueChanges.subscribe(v => {

  // When erasing the input field, cannot read toString() of null, can occur
  phoneControl.setValue((v && v.toString()) || null, { emitEvent: false });
});
0
laurensdewaele
<div nz-col [nzXs]="24" [nzSm]="12" nz-form-control nzHasFeedback>
                                <nz-input formControlName="password" [nzPlaceHolder]="'password'" [nzType]="'password'" [nzSize]="'large'" (ngModelChange)="validateConfirmPassword()">
                                </nz-input>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('minlength')">Your password must be at least 5 characters long. </div>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('maxlength')">Your password cannot exceed 15 characters. </div>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('required')">Please input your password!</div>
                            </div>
0
Tabish Zaman

Pour un champ number, vous pouvez valider les valeurs min et max à l'aide de la validation intégrée Angular, comme ceci:

. ts

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

private myNumberFieldMin: number = 1;
private myNumberFieldMax: number = 1000000;

constructor() {
      this.myForm = this.formBuilder.group({
        myNumberField
      })

this.myForm.controls.myNumberField.setValidators([
  Validators.min(this.myNumberFieldMin),
  Validators.max(this.myNumberFieldMax)
]);

html

<form [formGroup]="myForm">
  <input type="number" formControlName="myNumberField">

  <div *ngIf="this.myForm.controls['myNumberField'].errors && this.myForm.controls['myNumberField'].errors.min">
    <span class="error-message">Value must be at least {{myNumberFieldMin}}</span>
  </div>
  <div *ngIf="this.myForm.controls['myNumberField'].errors && this.myForm.controls['myNumberField'].errors.max">
    <span class="error-message">Maximum value is {{myNumberFieldMax}}</span>
  </div>
</form>
0
Chris Halcrow

Utilisez la méthode Compose () , composez plusieurs validateurs en une seule fonction.

Mettre à jour le fichier .TS comme ci-dessous,

this.myForm = this.formBuilder.group({ phone: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(12)])], message: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(100)])] });

0
Jitendra G2

La validation de formulaire de plusieurs paramètres ou de plusieurs conditions doit être composée comme un seul validateur, sinon vous obtiendrez une erreur observable ou une erreur de promesse:

phone: ['',  Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],
0
Sampath Kumar