I have a input field type number and I want to achieve the following scenario.
- Value length should be less than 5. (Max Length 5)
- 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 type="number" name="zip"
formControlName="zip" id="zip" placeholder="Enter a Zip Code" />
</div>
<button (click)="myFunction(myModal)"
type="button [disabled]="searchForm.invalid">Search
</button>
</form>
CodePudding user response:
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
