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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:28:57  来源:igfitidea点击:

ng-pattern doesn't show $error.pattern

javascriptangularjsformsvalidationangularjs-forms

提问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 scopevariable for that nameattribute value & do add all the form fields of the form which have nameattributes. Those fields attribute variable get created inside form scope object. Like here you are using myFormthat means $scope.myFromhas 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 subnetelement of form. You missed to add name="subnet"attribute on input field, that turns out to subnetelement validation doesn't available inside myFormscope 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}/" >

Working Plunkr

工作Plunkr