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>
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
Zip code validation
<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}$/;
Note:zip code available on string ex: PO14 1AS UK zip code
Just use default Pattern Validator
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}')
)),
})
}
And here are my imports :
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.