2016-08-16 76 views
0

用一个简单的形式:角1.5表单验证 - 如何验证多个输入都是空或满

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat"> 
    <input ng-model= "profile.dog" name="dog"> 
    <input ng-model= "profile.mouse" name="mouse"> 

</form> 

什么是验证所有三个输入已经被填充或空的最简单的方法?换句话说,只有当所有三个输入都被填充或者所有三个输入都为空时,表格才有效。我在一个自定义的验证多次尝试,一直以来把一个伪指令中的一个或多个的三个输入的线路,如:

<input ng-model= "profile.cat" name="cat" all-empty-all-full > 

自定义的验证:

function allEmptyAllFull() { 
    return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function (scope, element, attrs, ngModel) { 
     // nothing I put in here does the job! 
    } 
    } 
} 
angular 
    .module('app') 
    .directive('allEmptyAllFull', allEmptyAllFull); 

我已经尝试在链接函数中放入一个ngModel。$ validators.allEmptyAllFull函数,但在里面我无法访问其他两个输入。我已经看到了其他代码,其中人们在“比较”表单输入中放入了一个自定义属性,但在这种情况下,这并没有让我获得任何地方。任何帮助非常感谢。

编辑:我最初的问题措辞不佳,对不起。我不希望任何输入是独立需要的,但如果有人向其中的任何一个输入文本,则需要完成其他两个输入。全部或没有。

+0

您可以检查控制器。看到这个http://stackoverflow.com/questions/20054055/angularjs-check-if-form-is-valid-in-controller –

回答

0

为了使提交的所有三个输入的补扣,你可以做这样的事情。

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat" ng-required="simpleForm.dog.length > 0 || simpleForm.mouse.length > 0"> 
    <input ng-model= "profile.dog" name="dog" ng-required="simpleForm.cat.length > 0 || simpleForm.mouse.length > 0"> 
    <input ng-model= "profile.mouse" name="mouse" ng-required="simpleForm.cat.length > 0 || simpleForm.dog.length > 0"> 

    <button>Action</button> 
</form> 

只有当所有三个输入都具有某个值时,动作按钮才会启用。

+0

我也希望能够提交所有三个空的表格! – TDB

+0

所以你说,如果我没有在第一个文本框中输入任何内容,而其他两个都是空的,那么表单是有效的。但是如果我输入任何文本框,现在也需要其他两个文本框。 –

+0

是的,确切地说。我一直在努力工作一段时间,没有牵引。主要的问题是访问其他两个输入的值,而在一个自定义的验证器指令附加到我输入的输入。我可以想出其他解决方案,以防止直接从控制器提交表单(只需投入条件我的提交功能),但我想要一个更清洁的解决方案,使用ngModel。$ validators或$ setValidity。 – TDB

1

在必填字段中使用内置的必需指令。

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat" required> 
    <input ng-model= "profile.dog" name="dog" required> 
    <input ng-model= "profile.mouse" name="mouse" required> 
</form> 

,您可以检查的形式是有效

<button ng-disabled="simpleForm.$invalid">Action</button> 
+0

我需要比这更复杂的东西。我希望能够提交所有三个输入全部或全部三个输入空的表单 - 只是没有任何介于两者之间的任何东西。 – TDB

+0

@TDB,为什么不用'ng-disabled =“ctrl.isFormValid()”'用控制器中的函数? –