Javascript ng-pattern 不显示 $error.pattern
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31995684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-pattern doesn't show $error.pattern
提问by irom
I have script hereand ng-pattern works correctly because scope.subnet is shown in Output only after input matches pattern. But ng-show doesn't display any error if ng-pattern is not matched
我在这里有脚本并且 ng-pattern 工作正常,因为只有在输入匹配模式后,scope.subnet 才会显示在输出中。但是如果 ng-pattern 不匹配,ng-show 不会显示任何错误
<body ng-contoller="myConfigGenCtr">
<form novalidate name="myForm">
<div class="form-group">
<label for="hostname">Firewall hostname</label>
<input type="text" ng-model="hostname" class="form-control" id="hostname">
</div>
<div class="form-group">
<label for="subnet">Firewall subnet</label>
<input type="text" ng-model="subnet" class="form-control" id="subnet"
required ng-pattern="/^(?:[0-9]{1,3}\.){3}/" >
<div class="custom-error" ng-show="myForm.subnet.$error.pattern">
Not a valid subnet, should be i.e. 10.x.y. (3 bytes only)</div>
</div>
</form>
<div>Output: {{subnet}}</div>
</body>
回答by Pankaj Parkar
When you add form tag with its name, angular does create a scope
variable for that name
attribute value & do add all the form fields of the form which have name
attributes. Those fields attribute variable get created inside form scope object. Like here you are using myForm
that means $scope.myFrom
has all the information about the form fields. like its validity using $valid
, $invalid
, $error
, etc.
当您添加带有其名称的表单标签时,angular 会scope
为该name
属性值创建一个变量并添加具有name
属性的表单的所有表单字段。这些字段属性变量是在表单范围对象内创建的。就像这里您使用的myForm
那样,这意味着$scope.myFrom
拥有有关表单字段的所有信息。喜欢它的有效性使用$valid
,$invalid
,$error
,等。
Here you are using ng-show="myForm.subnet.$error.pattern"
on subnet
element of form. You missed to add name="subnet"
attribute on input field, that turns out to subnet
element validation doesn't available inside myForm
scope variable.
在这里,您正在使用ng-show="myForm.subnet.$error.pattern"
的subnet
表单元素。您错过了name="subnet"
在输入字段上添加属性,结果是subnet
元素验证在myForm
范围变量内不可用。
Markup
标记
<input type="text" name="subnet" ng-model="subnet" class="form-control"
id="subnet" required ng-pattern="/^(?:[0-9]{1,3}\.){3}/" >