admin管理员组

文章数量:1244304

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 ponent.ts

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./edit/angular-jfqkfo?file=src%2Fapp%2Fapp.ponent.ts

Share Improve this question edited Aug 22, 2018 at 7:32 user944513 asked Aug 22, 2018 at 7:12 user944513user944513 12.7k51 gold badges185 silver badges347 bronze badges 11
  • why are you using type="password" for this? Why not type="text" (I wouldn't use number as that'd remove any leading zeros of your mobile number) – monty Commented Aug 22, 2018 at 7:17
  • 1 second thing i need to mask my phohe number that why I used type="password" – user944513 Commented Aug 22, 2018 at 7:17
  • because I want to mask my phone number – user944513 Commented Aug 22, 2018 at 7:18
  • Is your Angular validator not working? – Kirk Larkin Commented Aug 22, 2018 at 7:21
  • @monty please suggest better solution – user944513 Commented Aug 22, 2018 at 7:23
 |  Show 6 more ments

6 Answers 6

Reset to default 4

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.

Add type="number" to your input element, that should automatically trigger the number pad rather than the regular keyboard on most devices.

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.

With HTML5, You could use the mon 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>

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;

}

本文标签: javascripthow to prevent user not to enter alphabets in input fiedStack Overflow