1

I'm wondering if there is an easy way to set this validation on a form text field, without creating a custom directive.

I need to validate that {minlength: 2, maxlength: 10}, user can enter any combination of [A-Z0-9\s], but only the amount of A-Z0-9 will go toward the minimum and maximum count.

Is this possible?

I was thinking maybe using ng-pattern and some magical regex might be able to pull this off. Just need a single error message to trigger if ng-pattern fails the match.

ngDeveloper
  • 1,304
  • 2
  • 16
  • 34

1 Answers1

2

The regular expression ^\s*(?:[A-Z0-9]\s*){2,10}$ will give what you are asking for. It breaks down as:

^\s*                            - start with 0 or more white space characters
       [A-Z0-9]                 - then one of A-Z or 0-9
               \s*              - then any number of additional 
                                  white space chars (including 0)
    (?:           ){2,10}       - repeat all that 2-10 times
                         \s*$   - and allow trailing white space

Edit: Updated to use non-capturing groups (which I did not realize ngPattern supported).

DocMax
  • 12,094
  • 7
  • 44
  • 44
  • Do patterns actually need to be anchored? I thought that's implicit. – Bergi Jun 16 '15 at 00:01
  • Awesome, thanks! You're really good with regex, how did you learn? Seems to work without the leading `\s*` as well (maybe because angular automatically trims whitespaces). Is there any way to change this to allow any character, including punctuation and whitespace, but only count the letters and numbers? – ngDeveloper Jun 16 '15 at 00:11
  • 1
    @ngDeveloper, Indeed, whitespace trimming _does_ do away with the need for the leading `\s*`. You should be able to allow any character by replacing `\s*` with `[^A-Z0-9]*` everywhere (including the leading one), although I have not tested that one. – DocMax Jun 16 '15 at 00:13