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

I am trying to create a contact form, I want the user to enter a phone number between a length of 10-12.

It is noteworthy that the same check works in the Message field, only in the number field, which causes me problems.

I found this answer, but it is useless to me.

I have code like:

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)]] });` 
+23
source share
10 answers

Update 1:

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

Used it as follows and worked perfectly:

  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; }; } } 
+11
source

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)])] }); } } 
+6
source

I have a trick that 100% works.

Define input like text, not number.

For instance:

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

Then use a template that is part of the validation.

Like:

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

This means that we determine the type of input text that is suitable for the minimum length, and we also define the template (validation) for the numeric value so that we can perform both checks.

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> 
+4
source

You should not use length here, since min and max use a special validator like this,

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

Angular2 min/max validators

+3
source
 <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
source

For the number field, you can check the minimum and maximum values ​​using the built-in angle check, for example:

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

Checking the form of several parameters or several conditions should be compiled as a single validator, otherwise you will receive an observed error or a promise error:

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

Use the Compose () method, compile several validators into one function.

Update the .TS file as shown below.

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
source

If you want to check a field with several validators, try this

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

Save the <input type="number"/> and just convert the int values ​​to strings.

 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
source

Source: https://habr.com/ru/post/1271661/


All Articles