简体   繁体   中英

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

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

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

Use && instead of ||

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

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.

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