Question

Can someone please tell me why my validations are not working. I followed many blogs and can't seem to debug it on my own.

<body data-ng-app="testapp">
<div data-ng-controller="testCtrl">
     <h1>Test {{name}}!!</h1>

    <form name="loginForm" action="login" novalidate>
        <input type="email" name="email" placeholder="email" required/>
        <input type="password" name="password" placeholder="password" required/>
        <button type="submit" ng-disabled="loginForm.$invalid">Login</button>
        <p ng-show="loginForm.$invalid">Please fix your form.</p>
        <p ng-show="loginForm.email.$invalid">Please fix your email.</p>
        <p ng-show="loginForm.password.$invalid">Please fix your password.</p>
    </form>
</div>
<script>
    var testapp = angular.module('testapp', []);
    var testCtrl = function($scope) {
        $scope.name = 'validation';
    };
</script>

http://jsfiddle.net/xFnx8/3/

Était-ce utile?

La solution

In order for Angular to track changes on form inputs, they need to be defined as ng-model properties on the scope.

So, your demo will work if you add the appropriate ng-model attributes:

<body data-ng-app="testapp">
<div data-ng-controller="testCtrl">
     <h1>Test {{name}}!!</h1>

    <form name="loginForm" action="login" novalidate>
        <input type="email" name="email" ng-model="email" placeholder="email" required/>
        <input type="password" name="password" ng-model="passowrd" placeholder="password" required/>
        <button type="submit" ng-disabled="loginForm.$invalid">Login</button>
        <p ng-show="loginForm.$invalid">Please fix your form.</p>
        <p ng-show="loginForm.email.$invalid">Please fix your email.</p>
        <p ng-show="loginForm.password.$invalid">Please fix your password.</p>
    </form>
</div>
<script>
    var testapp = angular.module('testapp', []);
    var testCtrl = function($scope) {
        $scope.name = 'validation';
    };
</script>

Here is a working fiddle.

Autres conseils

http://jsfiddle.net/6DzR5/

Yo, I fixed your fiddle.

You need to add your inputs as ng-model:

  <input type="email" name="email" placeholder="email" data-ng-model="email" data-ng-required="true"/>
  <input type="password" name="password" placeholder="password" data-ng-model="password" data-ng-required="true"/>

You must add an ng-model to your inputs so the form validation of angular can kick in.

Javascript

  var testapp = angular.module('testapp', []);
  var testCtrl = function ($scope) {
      $scope.name = 'validation';
      $scope.user = {};
  };

HTML modification

    <input type="email" name="email" placeholder="email" ng-model='user.email' required/>
    <input type="password" name="password" placeholder="password" ng-model='user.password' required/>

Working demo

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top