-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
4

4 回答 4

9

The ng-pattern should be as follows:

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

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

于 2016-10-04T08:05:44.163 回答
4

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

于 2016-10-04T17:47:27.853 回答
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>

于 2016-10-04T20:47:39.747 回答
1

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

pattern="^[a-zA-Z0-9_@.]+$"
于 2017-09-04T11:51:49.623 回答