2017-02-18 49 views
0

我正在使用anuglar.js表單驗證。 我想檢查沒有表單提交按鈕的驗證。驗證的角度形式不提交按鈕

這是我的html。

<form name="userForm"> 
    <input type="hidden" ng-model="StandardID" /> 
    <div class="form-group"> 
    <label for="email">Name:</label> 
    <input type="text" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required> 
    <span ng-show="userForm.Name.$dirty && !userForm.Name.$valid">Name is required.</span> 
    </div> 
    <div class="form-group"> 
    <label for="pwd">Alias:</label> 
    <input type="text" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required> 
    </div> 

    <button type="submit" class="btn btn-info" ng-click="update()">Submit</button> 
    <button type="submit" class="btn btn-info" data-dismiss="modal">Cancel</button> 
</form> 

我的控制器js是。

$scope.update= function() { 
    alert($scope.userForm.Name.$valid); 
    if ($scope.userForm.Name.$valid) { 
     alert("Entry added"); 
    } 
} 

它顯示說明該字段是必需的小對話框。我不想要這個彈出窗口。爲什麼跨度部分不顯示?

+0

無法正常工作。我之前做過,但我不知道這段代碼有什麼問題。爲什麼跨度部分沒有顯示。 – user3248761

回答

1

要做到這一點,關鍵是在<form>和所有輸入中使用name屬性。 按照這種方式,angularjs將創建一個表單實例,您可以訪問諸如myForm.myInput.$invalid

例如各個領域:

<form name="myForm" novalidate>  
    <label>My Input:</label> 
    <input type="text" name="myInput" ng-model="myInput" required> 
    <span ng-show="myForm.myInput.$dirty && !myForm.myInput.$valid">My Input is invalid.</span> 
</form> 

檢查角docs

+0

是的工作,但與此「請填寫此字段」通知對話框也可見。如何刪除它? – user3248761

+1

你在哪裏看到該通知?提交表單時瀏覽器是否通知?嘗試把

0

HTML

<div ng-app="myApp"> 
<form name="cutome_form" ng-submit="submitForm()" novalidate> 

    <input type="text" name="name" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required> 
           <div ng-show="cutome_form.name.$dirty && cutome_form.name.$invalid"> 
           <span class="error" ng-show="cutome_form.name.$error.required">The field is required.</span> 
           </div> 

       <div class="form-group"> 
          <label for="pwd">Alias:</label> 
          <input type="text" name="alias" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required> 
         </div> 
    <div ng-show="cutome_form.alias.$dirty && cutome_form.alias.$invalid"> 
     <span class="error" ng-show="cutome_form.alias.$error.required">The field is required.</span> 
    </div> 

    <button type="submit" ng-disabled="cutome_form.$invalid">Submit All</button> 
</form> 
</div> 

指令

.directive('ngModel', function() { 
    return { 
     require: 'ngModel', 
     link: function(scope, elem, attr, ngModel) { 
      elem.on('blur', function() { 
       ngModel.$dirty = true; 
       scope.$apply(); 
      }); 

      ngModel.$viewChangeListeners.push(function() { 
       ngModel.$dirty = false; 
      }); 

      scope.$on('$destroy', function() { 
       elem.off('blur'); 
      }); 
     } 
    } 
});