javascript 在同一页面上设置多个表单/验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33746155/
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
Setting up multiple forms / validations on same page
提问by WICS2 SRC
What's up all, total AngularJS noob here and looking for some answers.
怎么了,这里是 AngularJS 菜鸟,正在寻找一些答案。
I have a page set up like so:
我有一个页面设置如下:
<form name="mainForm" class="content" ng-app="pathForm" ng-controller="FormControl" novalidate>
<div class="full-page open" id="form1">
<!-- Form 1 content here -->
</div>
<div class="full-page" id="form2">
<!-- Form 2 content here -->
</div>
<div class="full-page" id="form3">
<!-- Form 3 content here -->
</div>
<div class="full-page" id="form4">
<!-- Form 4 content here -->
</div>
</form>
Where each of these forms have their own set of inputs that need validation. I've been able to get the validation working across all four forms, because I set up an encompassing form ng-app that cover all 4 forms. On submit, a script removes the 'open' class from the open form, cycles to the enxt form and adds the open class on that form.
这些表单中的每一个都有自己的一组需要验证的输入。我已经能够在所有四种表单中进行验证,因为我设置了一个涵盖所有 4 种表单的包含表单 ng-app。提交时,脚本从打开的表单中删除“打开”类,循环到 enxt 表单并在该表单上添加打开的类。
How can I set it so that each one of these forms can be individually validated?
如何设置它以便可以单独验证这些表单中的每一个?
Thanks in advance.
提前致谢。
采纳答案by Sharikov Vladislav
You need ngForm directiveand FormController.
Each ng-form directive with name in this directive adds property to the $scope
. You can access this property (it is object, instance of FormController) in function called by submit button click.
此指令中带有名称的每个 ng-form 指令都将属性添加到$scope
. 您可以在通过单击提交按钮调用的函数中访问此属性(它是对象,FormController 的实例)。
There are some properties and methods in this object. You need property $valid
(or $invalid
) to get validation status of your forms.
这个对象中有一些属性和方法。您需要属性$valid
(或$invalid
)来获取表单的验证状态。
HTML:
HTML:
<ng-form name="form1"></ng-form>
<ng-form name="form2"></ng-form>
<button ng-click="submit();">Submit</button>
JS:
JS:
$scope.submit = function () {
if ($scope.form1.$valid && $scope.form2.$valid) {}
}
Custom validatorsIf built-in validators are not enought you can add your own custom validators.
自定义验证器如果内置验证器不够用,您可以添加自己的自定义验证器。