0

How to combine this two regex for angularjs form field

\d{4}([- ]*)\d{6,7} 

OR

[a-zA-Z0-9]{4,12}

I tried like this

<input type="text" pattern="\d{4}([- ]*)\d{6,7} | [a-zA-Z0-9]{4,12}" class="form-control" ng-model="formData.username" required placeholder="username">
4
  • Sorry I tried but it not worked Commented May 7, 2016 at 12:27
  • Could you provide some sample strings to test against? How didn't your pattern work? What did it match/fail to match? Also, pattern is a HTML5 attribute, and you cannot have spaces around |. You can try with ng-pattern="/^(\d{4}([- ]*)\d{6,7}|[a-zA-Z0-9]{4,12})$/" Commented May 7, 2016 at 12:30
  • So, the problem was just a typo, those 2 spaces? Commented May 7, 2016 at 12:48
  • Why did you remove that other question? It may be useful for other people. Commented May 13, 2016 at 9:46

2 Answers 2

2

In order to get the alternative of 2 regular expressions, you need to wrap them both in parentheses:

<input type="text" pattern="(\d{4}([- ]*)\d{6,7})|([a-zA-Z0-9]{4,12})" class="form-control" ng-model="formData.username" required placeholder="username">
Sign up to request clarification or add additional context in comments.

3 Comments

It was my mistake, so that second regex is completely violating to the first one. so I made it like this : (\d{4}([- ]*)\d{6,7})|([a-zA-Z]{4,12})
Thanks your help fixed my problem
One does not have to put the alternative branches into capturing groups each, the only problem were the 2 spaces around |. pattern="\d{4}[- ]*\d{6,7}|[a-zA-Z0-9]{4,12}" should also work.
0

The problem is that angular uses single pipe symbol for filters and you are not allowed to use it within the templates. Usual case would be a binary OR but your case may also have the problem...

So what you can do is creating a variable on a controller which holds your pattern and use the variable in the template:

<input type="text" ng-pattern="myctrl.pattern" class="form-control" ng-model="formData.username" required placeholder="username">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.