简体   繁体   中英

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

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

正则表达式可视化

Regex101 Playground

HTML5 Demo:

Show code snippet

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

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)

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