I'm trying to use Angularjs validation to enable a button when at least one input from a list is filled 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 = '[email protected]';
});
</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?
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>
I'd use ng-required
for that case
<input ng-required="mustBeFilled()" ng-model="myModel" />
<input ng-required="mustBeFilled()" ng-model="myOtherModel" />
then
$scope.mustBeFilled = function () {
if($scope.myModel.length || $scope.otherModel.length){
return false
} else {
return true
}
}
so as soon as one input is filled the inputs won't be required, using require gives you control over some functionalities like using classes from form to display messages
and for submit button you can add
ng-disabled="formName.$invalid"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With