Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 364
Chocken Avatar asked Dec 05 '22 03:12

Chocken


2 Answers

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>
like image 102
okanozeren Avatar answered Dec 09 '22 13:12

okanozeren


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"
like image 37
maurycy Avatar answered Dec 09 '22 14:12

maurycy