ng-pattern 不适用于正则表达式

ng-pattern not working with regular expression

我的表单有以下内联验证

<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

使用&&代替||

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

您在 ng-pattern 属性上缺少双引号并且您还没有在页面上初始化 angular,您需要将 ng-app 添加到 运行 angular 第

标记

<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