Kalana Tebel
Kalana Tebel

Reputation: 105

How to accept only numeric numbers which has maximum 5 length for an input in Angular?

I have a input field type number and I want to achieve the following scenario.

  1. Value length should be less than 5. (Max Length 5)
  2. If above condition true only, submit button will enable.

Can someone help me on this?

.ts

 public searchForm: FormGroup = new FormGroup({
    zip: new FormControl("",[Validators.required,Validators.pattern(/^-?(0|[1-9]\d*)?$/), Validators.maxLength(5)]),
  });

.html

<form [formGroup]="searchForm">
          <div class = "form-group">
             <input class="form-control form-text-input" type="number" name="zip" 
              formControlName="zip" id="zip" placeholder="Enter a Zip Code" />
          </div>

          <button (click)="myFunction(myModal)" class="btn search-btn mb-1" 
           type="button [disabled]="searchForm.invalid">Search
          </button>
</form>

Upvotes: 1

Views: 6958

Answers (1)

HassanMoin
HassanMoin

Reputation: 2184

The maxLength is ignored on <input type="number"> Read: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-

You can use the max Validator to enforce a max length of 5

Hence your .ts will look like this.

 public searchForm: FormGroup = new FormGroup({
    zip: new FormControl("",[Validators.required,Validators.pattern(/^-?(0|[1-9]\d*)?$/), Validators.max(99999)]),
  });

Update

Another way to tackle this problem is IF type=number is not mandatory in your use case, is to remove type=number. Then the Regex that you are already using will do the validation for you and it will disable the button if the user does not input a number

Upvotes: 4

Related Questions