-2

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
13
  • 2
    Well, that was information that was useful to put in the question. Along with an minimal reproducible example demonstrating the problem. Commented Sep 29, 2016 at 8:49
  • 1
    I notice that the documentation says not to use the g flag. Commented Sep 29, 2016 at 8:50
  • 1
    and without the / ? 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_@.]+$/ ? Commented Sep 29, 2016 at 9:47
  • 3
    Works fine over here: plnkr.co/edit/lhkmD4UbR0aqEUofCUjD?p=preview Commented Sep 29, 2016 at 9:49

4 Answers 4

9
+25

The ng-pattern should be as follows:

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

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

Sign up to request clarification or add additional context in comments.

Comments

4

This will work for you.. ng-pattern= "/^[a-zA-Z0-9._@]+$/"

Comments

3

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>

Comments

1

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

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

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.