angularangular4-formsangular-validation

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


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>

Solution

  • 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