为什么 Angularjs ng-pattern 不能使用以下正则表达式? [英] Why is Angularjs ng-pattern not working with the following regexp?

查看:32
本文介绍了为什么 Angularjs ng-pattern 不能使用以下正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,初始化值没有出现在字段中,但没有 ng-pattern 的第二个字段确实有效.有什么想法吗?

 angular.module('app', []).controller('MainCtrl', function($scope) {$scope.widget = {title: 'abc', title2: 'abc'};});<div ng-app="app" ng-controller="MainCtrl"><input ng-model="widget.title" 需要 ng-pattern="/[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/"><br/><br/>输入 1: {{ widget.title }}<br/><br/><input ng-model="widget.title2" required><br/><br/>输入 2: {{ widget.title2 }}

这是小提琴http://jsfiddle.net/wkzab/1/

解决方案

UPDATE

我仔细研究了一下(从未真正使用过 Angular),通过在表单和输入中使用 name 属性,您可以获取一个错误,如我最新的 JSFiddle.它的格式为:{{formName.inputName.$error}}.这将返回一个参数等于布尔值的对象.所以 {{form.title.$error.pattern}} 将是 true 当正则表达式有错误时(所以你会显示错误).我还清理(工作相同)你的正则表达式:/^[A-Z]{4}\d{6}[A-Z\d]{3}$/i.

<小时>

ng-pattern 属性尝试根据此正则表达式匹配字段:<代码>/[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/.这将转换为 4 个字母字符、6 个数字和 3 个字母数字字符.一旦你有一个匹配的模式,它就会显示出来.

您应该能够删除 ng-pattern 属性或将表达式更改为不那么具体.例如,这个 JSFiddle 将接受任何值,只要整个字符串是字母数字.如果您需要其他模式的帮助,请更新问题.

For some reason the initialized value doesn't appear in the field, but the second field without the ng-pattern does work. any ideas?

    angular.module('app', []).controller('MainCtrl', function($scope) {
      $scope.widget = {title: 'abc', title2: 'abc'};
    });

    <div ng-app="app" ng-controller="MainCtrl">
     <input ng-model="widget.title" required ng-pattern="/[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/">
     <br /><br />   
     input 1: {{ widget.title }}
     <br /><br />   
     <input ng-model="widget.title2" required>
     <br /><br />   
     input 2: {{ widget.title2 }}
    </div>

Here is the Fiddle http://jsfiddle.net/wkzab/1/

解决方案

UPDATE

I looked into it a bit (never really used Angular), and by using the name attribute on the form and inputs, you can grab an error like shown in my newest JSFiddle. Its in the format: {{formName.inputName.$error}}. This returns an object with parameters that equal a boolean. So {{form.title.$error.pattern}} will be true when there is an error with the regular expression (so you would display the error). I also cleaned (works the same) your regex to: /^[A-Z]{4}\d{6}[A-Z\d]{3}$/i.


OLD

The ng-pattern attribute attempts to match the field based on this regular expression: /[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/. This translates to 4 alphabetical characters, 6 digits, and 3 alphanumeric characters. Once you have a matching pattern, it will show up.

You should be able to remove the ng-pattern attribute or change the expression to be less specific. For example, this JSFiddle will accept any value as long as the entire string is alphanumeric. Update the question if you want help with a different pattern.

这篇关于为什么 Angularjs ng-pattern 不能使用以下正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆