2014-06-23 151 views
1

我有一個表格表單驗證使用angularjs

<form name="formName"> 
<table> 
    <tr> 
     <td><input type="text" ng-model="validate" required/></td> 
    </tr> 
</table> 
</form> 
<button type="button" class="btn btn-default" ng-click="validate()">save</button> 

,你可以看到,該按鈕的形式外..我想驗證表單當我點擊該按鈕$ scope.validate();

問題是,我怎麼能實現使用angularjs?

+0

你得到任何錯誤? – thomasbabuj

+1

查看1.3中引入的令人敬畏的'ngMessages'指令進行表單驗證:http://www.yearofmoo.com/2014/05/how-to-use-ngmessages-in-angularjs.html – domokun

+0

nope but angularjs is實際上忽略我的確認......你能幫我嗎? @thomasbabuj –

回答

1

無論按鈕位於表單之外還是之外,都會在模型的任何屬性發生更改時始終執行驗證。所以剩下的唯一問題就是何時顯示錯誤信息。

btw要求是來自HTML5 ng-required是您應該使用的屬性。

下面顯示錯誤消息的代碼時的任何屬性改變

<div ng-app="mod"> 
<div ng-controller='MCtrl'> 
    <form name="formName" novalidate> 
     <table> 
      <tr> 
       <td> 
        <input type="text" name="prop" ng-model="model.property" ng-required="true" /> 
        <span ng-show="formName.prop.$error.required">Required</span> 
       </td> 
      </tr> 
     </table> 
    </form> 
    <button type="button" class="btn btn-default" ng-click="validate(formName)">save</button> 
</div> 

mod.controller('MCtrl', function ($scope) { 
    $scope.model = { property : ''}; 

    $scope.validate = function(form){ 
     alert(form.$valid); 
    } 

}); 

如果youd喜歡顯示的錯誤,只有當提交表單添加一個變量來跟蹤它像下面的代碼(注意ng-show中的附加變量=「formName.prop。$ error.required & & submitted」

<div ng-app="mod"> 
<div ng-controller='MCtrl'> 
    <form name="formName" novalidate> 
     <table> 
      <tr> 
       <td> 
        <input type="text" name="prop" ng-model="model.property" ng-required="true" /> 
        <span ng-show="formName.prop.$error.required && submitted">Required</span> 
       </td> 
      </tr> 
     </table> 
    </form> 
    <button type="button" class="btn btn-default" ng-click="validate(formName)">save</button> 
</div> 

mod.controller('MCtrl', function ($scope) { 
    $scope.model = { property : ''}; 
    $scope.submitted = false; 

    $scope.validate = function(form){ 
     $scope.submitted = true; 
     alert(form.$valid); 
    } 

}); 
+0

什麼你向我解釋的非常清楚..非常感謝你..它像魔術一樣工作! :) –