前面我示範了angular的表單驗證樣本:angularJS的表單驗證樣本 ,其實我們可以使用angular提供的模組messages進行更輕鬆的表單驗證,
<html> <head> <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> <script src="//cdn.bootcss.com/angular.js/1.4.4/angular.js"></script> <script src="angular-messages.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var app = angular.module('app', ['ngMessages']); app.controller('Ctrl',function () { }) </script> </head><style type="text/css"> .error{color: indianred;} .success{color: green;}</style> <body ng-app='app'> <div ng-controller="Ctrl"> <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label for="user" class="col-sm-2 control-label">使用者名稱</label> <div class="col-sm-5"> <input type="text" ng-model="user.username" name="user" ng-pattern="/^[a-zA-Z]\w{2,10}[a-zA-Z\d]$/" class="form-control" required="required"> </div> <div ng-messages="form.user.$error"> <div ng-message="required">必填項</div> <div ng-message="pattern">不符合</div> </div> </div> <button ng-disabled="form.$invalid">提交</button> </form> </div> </body></html>
html代碼不變,只是我們引入angular-messages.js檔案,在下面直接使用ng-message指令就可以很輕鬆的顯示我們想要顯示的內容