I have one input field of mobile where user can enter his/her number , but currently user can enter alphabets in input field.I want user will only enter 10 digit number not alphapets. here is my code
<section class="col-sm-12 bg-white pl-20 pr-20">
<div>
<form novalidate [formGroup]="cfForm">
<div class="form-group col-sm-4 pl-0">
<label class="field-title mb-5">Mobile Number</label>
<input type="password" placeholder="Enter Mobile no" formControlName="mobile_no">
</div>
</form>
{{cfForm.valid | json }}
{{cfForm.value | json}}
</div>
</section
TS file
constructor(private fb: FormBuilder){
this.cfForm = this.fb.group({
mobile_no: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
});
I don't want use type="number" or "text" .I want to use only "password" because i dont want to show my number to anyone see code https://stackblitz.com/edit/angular-jfqkfo?file=src%2Fapp%2Fapp.component.ts
Based on the discussion, you can restrict alphabets from getting entered using the code of the key pressed.
Refer to the below code:-
.ts:-
validateNumber(event) {
const keyCode = event.keyCode;
const excludedKeys = [8, 37, 39, 46];
if (!((keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 96 && keyCode <= 105) ||
(excludedKeys.includes(keyCode)))) {
event.preventDefault();
}
}
HTML:-
<input type="password" placeholder="Enter Mobile no" formControlName="mobile_no" (keydown)="validateNumber($event)">
You can refer to the stackblitz here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With