Thomas Murphy
Thomas Murphy

Reputation: 1468

angularJS: ng-pattern for multiple matches of pattern

It seems like a common way to validate values that are comma-separated is to split them into an array, then perform the regEx match on each member. However, I would like to take advantage of Angular's instant validation and perform this match in the view.

My regEx:

^\d{5}?,*$

works perfectly on the first match, but I'm at a loss as to how to ask it to check for this pattern n-times.

Form Code:

        <form id="zipCodeForm" name="zipCodeForm"  ng-submit="submit()" >
            <input id="zipCodeInput" ng-model="text" name="text" type="text"
            required ng-pattern="/^\d{5}?,*$/" > </input>

            <input id="zipSubmit" type="submit" value="Submit" class="btn btn-large btn-primary"></input>
            <div class="alert alert-info formatguide" ng-show="zipCodeForm.text.$dirty && zipCodeForm.text.$invalid">
               Enter Comma Separated 5-Digit Zip Codes ex.(11111,22222,33333)
            </div>
        </form>

Upvotes: 0

Views: 2754

Answers (1)

user557597
user557597

Reputation:

If you don't know how many zip codes, but want at least one, then this
^\d{5}(?:,\d{5})*$

If you know how many, use this
^\d{5}(?:,\d{5}){how many - 1}$

EDIT - The two regexes explained.

 ^                    # Begining of string
 \d{5}                # followed by 5 digits
 (?:                  # Cluster group
      ,                    # a literal comma
      \d{5}                # followed by 5 digits
 )*                   # End Cluster group, optionally do many times
 $                    # End of string

 # ---------------------------------------------------------

 ^                    # Begining of string
 \d{5}                # followed by 5 digits
 (?:                  # Cluster group
      ,                    # a literal comma
      \d{5}                # followed by 5 digits
 ){3}                 # End Cluster group, do exactly 3 times
 $                    # End of string

Upvotes: 3

Related Questions