Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent user not to enter alphabets in input fied?

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

like image 936
user944513 Avatar asked Dec 27 '25 23:12

user944513


1 Answers

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.

like image 96
Ankit Sharma Avatar answered Dec 30 '25 14:12

Ankit Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!