問題描述
我目前正在用 ionic 2 (Angular 2) 編寫一個簡單的表單.我想知道如何在驗證中添加一個簡單的 正則表達式 模式:
I'm currently writing a simple form in ionic 2 (Angular 2). I was wondering how I'd add a simple regular expression pattern to the validation:
我基本上有這個:
<form>
<ion-input stacked-label>
<ion-label>{{label.msisdn}}</ion-label>
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
pattern="06([0-9]{8})"
#msisdnForm="ngForm"
>
</ion-input>
<button [disabled]="!msisdnForm.valid" block (click)="requestActivationCode()">
{{label.requestActivationCode}}
</button>
</form>
最大長度、最小長度和required 正在被拾取(如果不滿足條件,按鈕將被禁用).現在我想將輸入限制為數字并在其前面加上 06(數字最少的荷蘭電話號碼).
The maxlength, minlength & required are being picked up (the button is disabled if conditions not met). Now I want to limit the input to numeric and prefix it with 06 (Dutch phone number with minimum amount of numbers).
但是,該模式并未在驗證中被選中.我可以這樣做,還是需要代碼方法?
The pattern is however not picked up in the validation. Can I do it this way, or do I need a code approach?
推薦答案
將模式添加到變量中
var pattern=/06([0-9]{8})/;
并將屬性綁定到它
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
[pattern]="pattern"
#msisdnForm="ngForm"
>
似乎這個 PR https://github.com/angular/angular/pull/6623/files 需要先登陸.
Seems this PR https://github.com/angular/angular/pull/6623/files needs to land first.
還有一個未解決的問題 https://github.com/angular/angular/issues/7595這可以防止 pattern
被綁定.該模式需要靜態添加到 DOM(無需綁定)才能工作.
There is still an open issue https://github.com/angular/angular/issues/7595
This prevents pattern
being bound to. The pattern needs to be statically added to the DOM (without binding) to work.
這篇關于使用模式 Angular 2 進行輸入驗證的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!