DivB
DivB

Reputation: 485

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

Upvotes: 1

Views: 1068

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136124

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

Upvotes: 1

Vino Spartan
Vino Spartan

Reputation: 83

Use && instead of ||

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

Upvotes: 0

Related Questions