表单验证不使用angularJS

时间:2014-12-05 15:05:46

标签: angularjs forms

我在桌子里面有一张表格。

    <table class='table table-bordered'>
        <caption>ADD NEW BRAND</caption>

        <tbody>
            <form ng-app="" class="form-horizontal" role="form" name="myForm">

                <div class="form-group">
                    <TR>
                        <TD>Brand Name</TD>

                        <TD>
                            <input type="text" class="form-control" name="name" ng-model="newbrand.Name" placeholder="Enter Brand Name" required>
                            <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
                                <span ng-show="myForm.name.$error.required">Brand Name is required.</span>
                            </span>
                        </TD>
                    </TR>
                </div>
            </form>
        </tbody>
    </table>

当输入字段为空时,它应指示需要品牌名称。但它不起作用。

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以使用指令执行此操作: - 举个例子:

html

  <body ng-controller="MainCtrl">
    <form novalidate class="person" name="personForm" test-directive validation="submitPerson" ng-submit="submitForm(personForm)">
      <h3>Person form</h3>
      <input type="text" required name="first-name" ng-model="person.firstName" ng-class="{'valid':personValid}" />
      <input type="submit" value="post" />
    </form>
  </body>

控制器&amp;指令

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

app.controller('MainCtrl', function($scope) {
  $scope.person = {
    firstName: 'Clem'
  };


  $scope.submitPerson = function(form, element) {
    console.log("Person validation here!")
    if(form.$valid) {
      $scope.personValid = true;
    }
    else {
      $scope.personValid = false;
    }
  };

});

app.directive('testDirective', function ($compile) {
  return {
    restrict: 'A',
    scope: true,
    link: function (scope, ele, attrs) {
      scope.submitForm = function(form) {
        eval("var fn = scope." + attrs.validation);
        fn(form, ele);
      }
    }
  };
})

信用: - Form validation in angular