Angular JS表单验证似乎不起作用

时间:2014-05-14 08:50:13

标签: angularjs validation

有人可以告诉我为什么我的验证无效。我关注了许多博客,似乎无法自己调试。

<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/

3 个答案:

答案 0 :(得分:3)

为了让Angular跟踪表单输入上的更改,需要将它们定义为范围上的ng-model属性。

因此,如果您添加适当的ng-model属性

,您的演示将会起作用
<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>

这是working fiddle

答案 1 :(得分:1)

http://jsfiddle.net/6DzR5/

哟,我修好你的小提琴。

您需要将输入添加为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"/>

答案 2 :(得分:1)

您必须在输入中添加ng-model,以便角度的表单验证可以启动。

<强>的Javascript

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

HTML修改

    <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