bielas
bielas

Reputation: 712

Make invalid form immediately after loading

I have a simple form written in AngularJS. I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.

<form name="myForm" ng-submit="myForm.$valid">

    <input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
    <input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
    <input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>

    <button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>



$scope.myForm = {};
        $scope.myForm.$valid = false;
        $scope.click=function () {
            console.log('-------------2', $scope.myForm);
        };

        $scope.onChange=function () {
            console.log('before:', $scope.myForm);
            var isValid = false;
            angular.forEach($scope.obj, function(value, key) {
                if(value == true){
                    isValid=true;
                }
                console.log(key + ': ' + value);
            });

            if(!isValid){
                $scope.myForm.$valid = false;
                $scope.myForm.$error.checkBoxes = {
                    isChecked: false
                };
            }

            console.log('after:', $scope.myForm);

        }

Upvotes: 0

Views: 60

Answers (2)

sahed moral
sahed moral

Reputation: 385

Try this in your submit button. hope it works

data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 56410

So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!

JSFiddle Demo

JS:

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
  $scope.onChange = function() {
    if ($scope.obj) {
      if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
        $scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
      } else {
        $scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
      }
    } else {
      $scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
    }
  }
});

Upvotes: 1

Related Questions