验证邮政编码在 Angular 4 中只允许长度为 5 或 7 位数字

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

我正在使用 Angular 4. 我想让 zipCode 输入字段只接受长度为 5 或 7 位的输入。

HTML代码:

<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>

我猜你想要 pattern 属性

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

其中 zipPattern 类似于 ^\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

邮政编码验证

<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>

zipPattern = /^[a-zA-Z0-9\s]{0,10}$/;

注意:字符串 ex 上可用的邮政编码:PO14 1AS 英国邮政编码

只需使用默认值模式验证器

HTML :

<form class="form" [formGroup]="settings_form">    
   <input type="number" placeholder="Code postal" formControlName="postalcode"/>
</form>

Component.ts :

public settings_form : FormGroup
ngOnInit() {

        this.settings_form = this.formBuilder.group({
          postalcode: new FormControl('', Validators.compose([
                                   Validators.required,
                                   Validators.pattern('[0-9]{5}')
                                   )),    
        })
       }

这是我的进口商品:

import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

您可以简单地按照下面我所遵循的邮政编码字段形式的最大长度和最大长度的数字模式进行操作:

 <input matInput [(ngModel)]="data.loc.zipcode" minlength="2" maxlength="6" pattern="[0-9]*" [errorStateMatcher]="customErrorStateMatcher" formControlName="zipcode" required>