簡體   English   中英

驗證郵政編碼在 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}$/;

注意:郵政編碼可用於字符串例如: PO14 1AS UK 郵政編碼

只需使用默認模式驗證器

HTML :

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM