Validate zipcode to only allow length 5 or 7 digits in Angular 4

sumit maske picture sumit maske · Jun 23, 2018 · Viewed 9.4k times · Source

I am using Angular 4. I want to allow the zipCode input field to only take an input of length 5 or 7 digits.

HTML code:

<md-input-container class="fill-width-input-wrap">
    <input mdInput placeholder="Zip Code" formControlName="zipCode" minLength="5" maxLength="7" (keypress)="allowOnlyNumbers($event)" required>
    <md-error *ngIf="clientInformationForm.controls['zipCode'].hasError('required')">
        Please enter
        <strong>valid zipcode</strong>
    </md-error>
    <md-error *ngIf="clientInformationForm.controls['zipCode'].hasError('minLength')">
        zip code
        <strong>minimum length is 5</strong>
    </md-error>
</md-input-container>

Answer

dhilt picture dhilt · Jun 23, 2018

I guess you want pattern attribute

<input mdInput formControlName="zipCode" 
       minLength="5" maxLength="7" 
       pattern="zipPattern" 
       (keypress)="allowOnlyNumbers($event)"
       required>
    <md-error *ngIf="clientInformationForm.controls['zipCode'].hasError('pattern')">
        zip code must satisfy pattern
    </md-error>
    ...

Where zipPattern is something like ^\d{5}(?:\d{2})?$:

const pattern = new RegExp(/^\d{5}(?:\d{2})?$/)
'1234'.match(pattern) // null
'12345'.match(pattern) // ["12345"
'123456'.match(pattern) // null
'1234567'.match(pattern) // ["1234567"
'12345678'.match(pattern) // null