AngularJS check if form is valid in controller
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
Solution 1:
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
}
};
Solution 2:
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;
});
...