2015-04-23 62 views
1

我的形式有以下在線驗證NG模式不與正則表達式的工作

<form name="coForm" novalidate> 
<div> 
    <label>Transaction: </label> 
    <input type="text" name="transaction" class="form-control" 
      placeholder="<Direction> <Message Type>, ex.:OUT X12214" 
      ng-model="newco.transaction" 
      ng-pattern=/(^(IN)([A-Za-z0-9 &_]+))|(^(OUT)([A-Za-z0-9 &_]+))/ 
    required> 

     <span style="color:red" 
     ng-show="coForm.transaction.$dirty || 
        coForm.transaction.$invalid"> 
     <span ng-show="coForm.transaction.$error.pattern"> 
      Enter correct value for Transaction 
     </span> 
     <span ng-show="coForm.transaction.$error.required"> 
      Transaction is required. 
     </span> 
</div> 
</form> 

但驗證僅適用於required而不是pattern

Here is the fiddle

下面是幾個例子正匹配:

OUT X12214 
In X12850 
IN ARRANT 
OUT CORREC&TRANSLEG 
OUT TEST_TEST 
IN TEST2&TEST2 
+0

之前問問題請縮進你的代碼。 –

回答

1

你失蹤的ng-pattern屬性&的雙引號,你也沒有初始化頁面上的角度,你需要添加ng-app到網頁上運行的角度

標記

<form name="coForm" novalidate ng-app=""> 
    <div> 
     <label>Transaction:</label> 
     <input type="text" name="transaction" class="form-control" placeholder="<Direction> <Message Type>, ex.:OUT X12214" ng-model="newco.transaction" 
     ng-pattern="/(^(IN)([A-Za-z0-9 &_]+))|(^(OUT)([A-Za-z0-9 &_]+))/" required> 
     <span style="color:red" ng-show="coForm.transaction.$dirty || coForm.transaction.$invalid"> 
      <span ng-show="coForm.transaction.$error.pattern">Enter correct value for Transaction</span> 
      <span ng-show="coForm.transaction.$error.required">Transaction is required.</span> 
     </span> 
    </div> 
</form> 

JsFiddle

+0

非常感謝。這是行得通的。 – DivB

+0

@DivB很高興幫助你,謝謝:-) –

0

使用&&而不是||

ng-show="coForm.transaction.$dirty && 
       coForm.transaction.$invalid"> 
+0

這不起作用。我在表單中添加了一個更簡單的字段,這在jsfiddle中也不起作用。但是新添加的字段「CO Number:」適用於我的應用程序。 [這是更新的小提琴](http://jsfiddle.net/DivB/pwan5L0g/5/) – DivB