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

前端 未结 12 960
被撕碎了的回忆
被撕碎了的回忆 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:40

    This trick will be helpful

    In .html file

     
    

    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}$')
    

提交回复
热议问题