简体   繁体   中英

Angular ng-pattern regex not working

I'm trying to create a validation for an angular input field which accepts only the a-zA-Z0-9 characters and special characters ".”(full stop), "_" (underscore), "@"(at sign)

I can't seem to get the hang of it.

I tried:

ng-pattern="/[a-zA-Z0-9_@.]+/"

requirement:

  • It can contain only alphabetic characters
  • it can contain alphabetic and numeric
  • It can contain alphabetic numeric and mentioned special characters
  • It cannot contain space

The ng-pattern should be as follows:

ng-pattern="/^[a-zA-Z0-9_@.]+$/" 

See demo here: http://plnkr.co/edit/ElBuuxGilBbC9fdA2n0P?p=preview

这对你有用.. ng-pattern="/^[a-zA-Z0-9._@]+$/"

Here are the "blocks" to write the final solution:

It can contain only alphabetic characters - Use ^[a-zA-Z]+$
it can contain alphabetic and numeric - Use ^[a-zA-Z0-9]+$
It can contain alphabetic numeric and mentioned special characters - Use ^[a-zA-Z0-9_@.]+$
It cannot contain space - Use ng-trim="false" (see this SO thread )

JS full demo:

 var app = angular.module("app", []);
 <html ng-app="app"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body> <form name="form"> <p>Enter text to validate:</p> <input type="text" ng-model="name" name="name" ng-pattern="/^[a-zA-Z0-9_@.]+$/" ng-trim="false" /> <div ng-show="form.name.$error.pattern">Text doesn't match with ng-pattern!</div> </form> </body> </html>

Just to add up to date information. If you use Angular4 it should be:

pattern="^[a-zA-Z0-9_@.]+$"

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