Jimi
Jimi

Reputation: 1897

ng-pattern regex to match multiple conditions

I'm using ng-pattern to validate a field for the following conditions. Thus far I'm only able to validate the last two conditions using the following regex. When I add only numbers, I'd like to validate the length as well.

How can I validate all four conditions inside ng-patter? Do I need to surround then with brackets separately?

data-ng-pattern="/^[0-9-\s()+]+$/"

11111111
111111111
11-111-111
111-111-111

I'd like to validate multiple conditions

Upvotes: 0

Views: 1144

Answers (2)

Harish Verma
Harish Verma

Reputation: 556

The problem with ^[1-9][0-9]{6}*$ is it is an invalid regex because of {6}* and ^([^0][0-9]){6}$ is that it is allowing any character that is not 0 followed by six digits.

Use

^[1-9][0-9]{5}$

Explanation:

  1. ^: Starts with anchor
  2. [1-9]: Matches exactly one digit from 1 to 9
  3. [0-9]{5}: Matches exactly five digits in the inclusive range 0-9
  4. $: Ends with anchor

Regex Visualization

Regex101 Playground

HTML5 Demo:

Show code snippet

input:invalid { color: red; } <input type="text" pattern="[1-9][0-9]{5}" /> Run code snippetHide results

Upvotes: 1

Keyur Shah
Keyur Shah

Reputation: 536

try this. it will only allow 10 digits.

/^[1-9]{1}[0-9]{9}$/

i'm not sure this would work but i tried.

/^[1-9]{1}[0-9-\s()+]{10}$/gm

Explainlation

1) ^ Beginning. Matches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled.

2) [ Character set. Match any character in the set. 1-9 Range. Matches a character in the range "1" to "9" (char code 49 to 57). ]

3) {1} Quantifier. Match 1 of the preceding token.

4) [ Character set. Match any character in the set.

5) 0-9 Range. Matches a character in the range "0" to "9" (char code 48 to 57).

6) - Character. Matches a "-" character (char code 45).

7) \s Whitespace. Matches any whitespace character (spaces, tabs, line breaks).

8) ( Character. Matches a "(" character (char code 40).

9) ) Character. Matches a ")" character (char code 41).

10) + Character. Matches a "+" character (char code 43). ]

11) {10} Quantifier. Match 10 of the preceding token.

12) $ End. Matches the end of the string, or the end of a line if the multiline flag (m) is enabled.

13) g modifier: global. All matches (don't return on first match)

14) m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Upvotes: 0

Related Questions