function demoCtrl($scope) { $scope.reset = function() { $scope.user = {}; $scope.demoForm.$setPristine(); } }
<div ng-app> <div ng-controller="demoCtrl"> <h1>表單驗證Demo</h1> <input type='button' value='重置表單' ng-click='reset()'> <form name="demoForm"> <table border='1px'> <tr> <td><span class='notice'>(必填)</span>姓名:</td> <td> <input type='text' name='name' ng-model='user.name' required> <span class='error' ng-show='demoForm.name.$error.required && demoForm.name.$dirty'>請輸入</span> </td> </tr> <tr> <td><span class='notice'>(必填)</span>性別:</td> <td> <input type='radio' name='sex' ng-model='user.sex' value='M' required>男 <input type='radio' name='sex' ng-model='user.sex' value='F' required>女 <span class='error' ng-show='demoForm.sex.$error.required && demoForm.sex.$dirty'>請輸入</span> </td> </tr> <tr> <td><span class='notice'>(必填)</span>生日:</td> <td> <input type='date' name='birthday' ng-model='user.birthday' required> <span class='error' ng-show='demoForm.birthday.$error.required && demoForm.birthday.$dirty'>請輸入</span> </td> </tr> <tr> <td><span class='notice'>(必填)</span>地址</td> <td> <input type='number' class='zipcode' name='zipcode' ng-model='user.zipcode' required ng-maxlength='3' ng-minlength='3'> <span class='error' ng-show='demoForm.zipcode.$invalid && demoForm.zipcode.$dirty'>格式驗證錯誤</span> <span class='error' ng-show='demoForm.zipcode.$error.required && demoForm.zipcode.$dirty'>請輸入</span> <br> <input type='text' name='address' ng-model='user.address' required> <span class='error' ng-show='demoForm.address.$error.required && demoForm.address.$dirty'>請輸入</span> </td> </tr> <tr> <td><span class='notice'>(必填)</span>電子郵件:</td> <td> <input type='email' name='email' ng-model='user.email' required> <span class='error' ng-show='demoForm.email.$invalid && demoForm.email.$dirty'>格式驗證錯誤</span> <span class='error' ng-show='demoForm.email.$error.required && demoForm.email.$dirty'>請輸入</span> </td> <tr> <td>聯絡電話:</td> <td> <input type='text' name='contectPhone' ng-model='user.contectPhone'> </td> </tr> </table> <div> <h3>資料:</h3>{{user}} </div> <div> <h3>表單驗證結果:</h3>{{demoForm.$valid}} </div> </form> </div> </div>
.zipcode { width: 40% } .notice { color: green } .error { color: red }