简体   繁体   中英

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

type="number"添加到您的input元素,这应该会自动触发数字键盘而不是大多数设备上的常规键盘。

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.

With HTML5, You could use the common attribute pattern .

(And also inputmode in some browsers)

Reference here

A regex pattern to force 10 digits: ^[0-9]{10}$

Example:

 <form action="javascript: alert('alright');"> <div> <input type="password" pattern="^[0-9]{10}$" minlength="10" maxlength="10" placeholder="Enter Mobile no" required title="Ten digits required."> <input type="submit"> </div> </form>

firstly you can add maxlength attribute to your input field, that will allow only 10 characters to be passed. Like this below:

Now for only Numeric characters validation, i suggest you should create a directive and use that directive in all the places, where you need Numbers only validation.

.html

    <form novalidate [formGroup]="cfForm">

        <div class="form-group col-sm-4 pl-0">
          <label class="field-title mb-5">Mobile Number</label>
          <input NumbersOnly="true" type="password" placeholder="Enter Mobile no" formControlName="mobile_no" maxlength="10">
        </div>


    </form>
    {{cfForm.valid | json }}
    {{cfForm.value | json}}
  </div>
</section>

NumbersOnly.directive.ts

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[NumbersOnly]'
})
export class NumbersOnlyDirective {

 constructor(private el: ElementRef) { }

 @Input() NumbersOnly: boolean;


 @HostListener('keydown', ['$event']) onKeyDown(event) {
 let e = <KeyboardEvent> event;
 if (this.NumbersOnly) {
  if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
    // Allow: Ctrl+C
    (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
    // Allow: Ctrl+V
    // (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
    // Allow: Ctrl+X
    (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39)) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
  }
}
}

Like this way you can achieve what you desire. The main advantage of using this approch is that, in your whole project , whereever you need Number Only validation, you can simple add NumbersOnly = true inside the input field, and it will handle the rest.

Visit this to know more about Directives .

use preventDefault() method and regex
HTML

 <input type="password" (keypress)="matcher($event)"
    placeholder="Enter Mobile no" formControlName="mobile_no">

Component:

 public matcher(event) {
        const allowedRegex = /[0-9]/g;

        if (!event.key.match(allowedRegex)) {
            event.preventDefault();
        }
    }

You need to add an event to check whether the input is Number or Alphabet. Just add the event in input field

<input type="password" placeholder="Enter Mobile no" formControlName="mobile_no" (keypress)="numberOnly($event)">

In the TS file

numberOnly(event): boolean {
const charCode = event.which ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
  return false;
}
return true;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM