Reputation: 105
I have a input field type number and I want to achieve the following scenario.
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
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)]),
});
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