9

I want to check if a form is valid inside an angular controller. This seems straightforward when using $scope, but I can't get it to work with the 'controller as' syntax.

When I attempt to access form.$valid I get the error message "Cannot read property '$valid' of undefined".

plunkr: http://plnkr.co/edit/w54i1bZVD8UMhxB4L2JX?p=preview

HTML

<div ng-app="demoControllerAs" ng-controller="MainController as main">
  <form name="contactForm" novalidate>
    <p>
      <label>Email</label>
      <input type="email" name="email" ng-model="main.email" required />
    </p>
    <p>
      <label>Message</label>
      <textarea name="message" ng-model="main.message" required></textarea>
    </p>
    <input type="submit" value="submit" ng-click="main.submit()" />
  </form>
</div>

JS

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

app.controller('MainController', [function () {
    var main = this;

    main.submit = function () {
        var isValid = main.contactForm.$valid;
        console.log(isValid);
    };
}]);

4 Answers 4

11

You could do as @ons-jjss suggested but if you prefer not to inject $scope into you controller, then just change your form name as

<form name="main.contactForm" novalidate>

and it'll work like a charm.

Sign up to request clarification or add additional context in comments.

3 Comments

This solution is not intuitive. You are already using $scope in template. You should inject $scope to controller instead of prefixing a form name with weird names such as "main", "$ctrl" or "$vm".
Yes.. you got it.
@ismailarilik what's intuitive is matter of perspective, maybe? stackoverflow.com/a/30644370/1061668
4

You need to use in this way: $scope.contactForm.$valid

EDIT

To work the above syntax, $scope needs to be inhjected in controller.

app.controller('MainController', function($scope) { 
  //code 
} 

2 Comments

Doesn't work. $scope is not defined. plnkr.co/edit/HIwmTvLs0wg6Kt7244vM?p=preview
I guess you did not inject $scope. app.controller('MainController', function($scope) { //code }
0

You need to use main.contactForm in form name attribute then it's solved. See this

`http://plnkr.co/edit/us8MKU3LZ7pnLV66xIrv?p=preview`

Comments

-1

You can pass your form as a parameter to function submit as ng-click="main.submit(contactForm)

and then validate it in controller method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.