Search code examples
javascriptregexangularjsng-patternng-maxlength

Validate A-Z0-9 has maxlength 10, but allow user to enter spaces (but skip spaces in maximum)


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.


Solution

  • 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).