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
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
- 2 Well, that was information that was useful to put in the question. Along with an minimal reproducible example demonstrating the problem. – T.J. Crowder Commented Sep 29, 2016 at 8:49
-
1
I notice that the documentation says not to use the
g
flag. – T.J. Crowder Commented Sep 29, 2016 at 8:50 -
1
and without the
/
? – LukStorms Commented Sep 29, 2016 at 9:14 -
1
The documentation doesn't seem to show an example of an ng-pattern with regex that's not put in a string. But maybe you could test it anyway with
ng-pattern=/^[a-zA-Z0-9_@.]+$/
? – LukStorms Commented Sep 29, 2016 at 9:47 - 3 Works fine over here: plnkr.co/edit/lhkmD4UbR0aqEUofCUjD?p=preview – Jamie Barker Commented Sep 29, 2016 at 9:49
4 Answers
Reset to default 9 +25The ng-pattern should be as follows:
ng-pattern="/^[a-zA-Z0-9_@.]+$/"
See demo here: http://plnkr.co/edit/ElBuuxGilBbC9fdA2n0P?p=preview
This will work for you.. 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 - Useng-trim="false"
(see this SO thread)
JS full demo:
var app = angular.module("app", []);
<html ng-app="app">
<head>
<script src="https://ajax.googleapis./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_@.]+$"