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

前端 未结 12 963
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 18:06

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

相关标签:
12条回答
  • 2021-01-03 18:35

    The Form Validation of multiple parameters or multiple conditions should be composed as single validator otherwise you will get observable or promise error:

    phone: ['',  Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],
    
    0 讨论(0)
  • 2021-01-03 18:38

    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)])]
            });
    }
    }
    
    0 讨论(0)
  • 2021-01-03 18:40

    This trick will be helpful

    In .html file

     <input type="text" (keyup)="onKeyUp($event)" formControlName="phone" placeholder="Phone Number">
    

    In .ts file

    The below code restrict string characters

        public onKeyUp(event: any) {
        const NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
        let newValue = event.target.value;
        let regExp = new RegExp(NUMBER_REGEXP);
    
        if (!regExp.test(newValue)) {
          event.target.value = newValue.slice(0, -1);
        }
       }
    

    and other validation

    phone: ['', Validators.compose([
            Validators.required, 
             Validators.pattern('^[0-9]{0,30}$')])
          ])],
    

    The above pattern code allow number upto 30 digits. If you want minimum two digits, you can do like this

     Validators.pattern('^[0-9]{2,30}$')
    
    0 讨论(0)
  • 2021-01-03 18:43

    Keep <input type="number" /> and just transform 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 讨论(0)
  • 2021-01-03 18:45

    Use Compose() method, compose multiple validators into a single function.

    Update .TS file as 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 讨论(0)
  • 2021-01-03 18:46

    Update 1 :

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

    Used it like following 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;
        };
      }
    }
    
    0 讨论(0)
提交回复
热议问题