AngularJs_FormValidationDemo

Form Validation in AngulaarJs.

by Ryan Hsu

HTML

<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'...

CSS

.zipcode {
  width: 40%
}

.notice {
  color: green
}

.error {
  color: red
}

JavaScript

function demoCtrl($scope) {
  $scope.reset = function() {
    $scope.user = {};
    $scope.demoForm.$setPristine();
  }
}