Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS check if form is valid in controller

Tags:

angularjs

I need to check if a form is valid in a controller.

View:

<form novalidate=""       name="createBusinessForm"       ng-submit="setBusinessInformation()"       class="css-form">  <!-- fields --> </form> 

In my controller:

.controller(     'BusinessCtrl',     function ($scope, $http, $location, Business, BusinessService,                UserService, Photo)     {          if ($scope.createBusinessForm.$valid) {             $scope.informationStatus = true;         }          ... 

I'm getting this error:

TypeError: Cannot read property '$valid' of undefined 
like image 692
Rober Avatar asked Nov 18 '13 17:11

Rober


People also ask

How do you check whether a form is valid or not in AngularJS?

The form instance can optionally be published into the scope using the name attribute. So to check form validity, you can check value of $scope. yourformname. $valid property of scope.

Which is the valid statement of controller in AngularJS?

ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application.

What is $dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.

What is $Setpristine in AngularJS?

Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.


2 Answers

Try this

in view:

<form name="formName" ng-submit="submitForm(formName)">  <!-- fields --> </form> 

in controller:

$scope.submitForm = function(form){   if(form.$valid) {    // Code here if valid   } }; 

or

in view:

<form name="formName" ng-submit="submitForm(formName.$valid)">   <!-- fields --> </form> 

in controller:

$scope.submitForm = function(formValid){   if(formValid) {     // Code here if valid   } }; 
like image 145
Damsorian Avatar answered Oct 14 '22 11:10

Damsorian


I have updated the controller to:

.controller('BusinessCtrl',     function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {         $scope.$watch('createBusinessForm.$valid', function(newVal) {             //$scope.valid = newVal;             $scope.informationStatus = true;         });         ... 
like image 21
Rober Avatar answered Oct 14 '22 10:10

Rober