简体   繁体   中英

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>

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

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