Anthony
Anthony

Reputation: 2416

Prevent user from entering letters in angular reactive form

I am building an angular 4 reactive form. So far I have the following validation rules for last 4 ssn:

  last4Ssn: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(4), Validators.pattern('^[0-9]+$')]],

Template:

<label>Last 4 SSN
  <input formControlName="last4Ssn" >
  {{ shortForm.get('last4Ssn').errors | json }}
  <div
    class="error"
    *ngIf="shortForm.get('last4Ssn').hasError('required') && shortForm.get('last4Ssn').touched">
    Name is required
  </div>
  <div
    class="error"
    *ngIf="shortForm.get('last4Ssn').hasError('minlength') && shortForm.get('last4Ssn').touched">
    Minimum of 4 characters
  </div>
</label>

This correctly calls out errors. For example if I type "dn4" I get the following printed out:

{ "minlength": { "requiredLength": 4, "actualLength": 3 }, 
  "pattern": { "requiredPattern": "^^[0-9]+$$", "actualValue": "dn#" } } 

How can I actually prevent the user from typing letters or special characters? Is that outside the built in functionality of angular and I need to build something custom?

Upvotes: 2

Views: 2738

Answers (2)

Anthony
Anthony

Reputation: 2416

Get keycode, convert to string, run through regex.

numbersOnlyValidation(event){    
 const inp = String.fromCharCode(event.keyCode);    
 /*Allow only numbers*/
  if (!/^\d+$/.test(inp)){
   event.preventDefault()
  }    
 }

Upvotes: 1

Nehal
Nehal

Reputation: 13307

I found a simple function that stops user from typing anything except numbers. I bind it with keypress event that takes care of the rest.

onlyNumberKey(event){
        let charCode = (event.query) ? event.query : event.keyCode;
        console.log(charCode);
            if (charCode > 31
                && (charCode < 48 || charCode > 57))
                return false;

            return true;
    }

HTML:

<md-input-container>
  <input mdInput placeholder="Last 4 SSN" (keypress)="onlyNumberKey($event)">
</md-input-container>

Plnkr demo

Upvotes: 2

Related Questions