Skip to content Skip to sidebar Skip to footer

Angularjs - Form Custom Validation - Check If At Least One Input Is Empty

Given a simple html form like this:
Copy

!!str is to force to convert str to a boolean value. And both !!null and !!"" are evaluated to be false.

Demo

Solution 2:

You can set the "required" in the input elements and style / code how you want to handle with $valid of a form. Check out http://dailyjs.com/2013/06/06/angularjs-7/

Solution 3:

My solution was the following:

$scope.requiredInputsGroup = function () {
            var isRequired = true;
            if (!$scope.shipment) {
                returntrue;
            }
            angular.forEach(["userPreference1", "userPreference2", "userPreference3"], function (input) {
                if ($scope.shipment[input]) {
                    isRequired = false;
                    returnfalse;
                }
            });

            return isRequired;
        };

You apply that method to a data-ng-required in each of the inputs...

<form name="myForm" action="#sent" method="post" ng-app>
   <input name="userPreference1"type="text" ng-model="shipment.userPreference1" ng-required="requiredInputsGroup()" />
   <input name="userPreference2"type="text" ng-model="shipment.userPreference2" ng-required="requiredInputsGroup()" />
   <input name="userPreference3"type="text" ng-model="shipment.userPreference3" ng-required="requiredInputsGroup()" />

   <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

And the last bit I applied was to make the button disabled with a simple myForm.$invalid

Post a Comment for "Angularjs - Form Custom Validation - Check If At Least One Input Is Empty"