简体   繁体   English

ng-pattern无法使用正则表达式

[英]ng-pattern not working with regular expression

My form has below inline validation 我的表单具有以下内联验证

<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>

But the validation works only for required and not for pattern 但是验证仅适用于required ,不适用于pattern

Here is the fiddle 这是小提琴

Below are the few examples for positive match: 以下是一些正面匹配的示例:

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

You were missing double quotes on of ng-pattern attribute & also you have not initialize angular on page, you need to add ng-app to run angular on page 您缺少ng-pattern属性的双引号,并且还没有初始化页面上的angular,您需要添加ng-app才能在页面上运行angular

Markup 标记

<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 的jsfiddle

Use && instead of || 使用&&代替||

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM