Chocken Chocken - 4 months ago 21
AngularJS Question

Angularjs Validation: Require at least one input from a list

I'm trying to use Angularjs validation to enable a button when at least one input from a list is filed in. What I'm working on is similar to the following w3schools example:




<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body>
<h2>Validation Example</h2>

<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>

<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid>"
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>

</body>




I tried adding a div containing two inputs with a "required" tag as follows but to no avail:

<div name="address" ng-model="address" required>
<input name="address1" ng-model="address1">
<input name="address2" ng-model="address2">




What would be the best way to do this with angular validation?

Answer

The ng-required directive can help you for your this like conditional requirement needs.

For example:

<div name="addresses">
  <input name="address1" ng-model="address1" ng-required="!address2">
  <input name="address2" ng-model="address2" ng-required="!address1">
</div>
Comments