10 digit Regex Validation with angularJs ng-Pattern

Muhammad Adeel Zahid picture Muhammad Adeel Zahid · Mar 24, 2015 · Viewed 8.9k times · Source

I want one of my input fields to have exactly 10 digits. I have used ng-pattern in following manner

<input type="text" ng-pattern="/[1-9]{1}[0-9]{9}$/" ng-model="user.Identity" name="identity">

The problem is that this expression is allowing the user to enter numeric strings having more than 10 digits whereas, I want to allow exactly 10 digits. Is there a problem with my regex or my understanding of ng-pattern?

Answer

Alex K. picture Alex K. · Mar 24, 2015

The ^ anchor indicates start of string/line as $ does for the end, ^expr$ prevents the shifting window matches you see:

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