Angular ng-pattern 正则表达式不工作

Angular ng-pattern regex not working

我正在尝试为 angular 输入字段创建验证,该字段仅接受 a-zA-Z0-9 字符和特殊字符“.”(句号)、“_”(下划线) ), "@"(at 符号)

我似乎无法掌握它。

我试过:

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

要求:

ng 模式应如下所示:

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

在此处查看演示:http://plnkr.co/edit/ElBuuxGilBbC9fdA2n0P?p=preview

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

下面是"blocks"写的最终解决方案:

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 )

JS 完整演示:

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>

只是为了添加最新信息。如果你使用 Angular4,它应该是:

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