AngularJS中的表單驗證


AngularJS中的表單驗證

AngularJS自帶了很多驗證,什么必填,最大長度,最小長度...,這里記錄幾個有用的正則式驗證

Note that novalidate is used to disable browser's native form validation. 用來禁用H5的原生驗證.

1.使用angularjs的表單驗證

正則式驗證
只需要配置一個正則式,很方便的完成驗證,理論上所有的驗證都可以用正則式完成

    //javascript
    $scope.mobileRegx = "^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$";
    $scope.emailRegx = "^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$";
    $scope.pwdRegx = "[a-zA-Z0-9]*";
<div class="form-group">
    <input class="form-control" name="mobile" type="text" ng-model="account.mobile" required ng-pattern="mobileRegx"/>
    <span class="error" ng-show="registerForm.$submitted && registerForm.mobile.$error.required">*手機號不能為空</span>
    <span class="error" ng-show="registerForm.$submitted && registerForm.mobile.$error.pattern">*手機號地址不合法</span>
</div>
<input type="text" ng-pattern="/[a-zA-Z]/" /> 

數字
設置input的type=number即可

    <div class="form-group col-md-6">
        <label for="password">
            預估時間
        </label>
        <div class="input-group">
            <input required type="number" class="form-control" ng-model="task.estimated_time" name="time" />
            <span class="input-group-addon">分鍾</span>
        </div>
        <span class="error" ng-show="newTaskForm.$submitted && newTaskForm.time.$error.required">*請預估時間</span> 
    </div>

郵箱

<input type="email" name="email" ng-model="user.email" /> 

URL

<input type="url" name="homepage" ng-model="user.facebook_url" />

效果
效果是實時的,很帶感

2.使用ngMessages驗證表單

相對於上面的每個驗證都要自己寫代碼判斷,ngMessages提供了一種更為簡潔的方式
https://docs.angularjs.org/api/ngMessages/directive/ngMessages

angular.module('ngMessagesExample', ['ngMessages']);
<form name="myForm">
  <label>
    Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="5"
           ng-maxlength="20"
           required />
  </label>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
  <!--需要配合 ng-if使用,否則一開始就顯示出來了, 你摸了就會觸發驗證--> 
  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert" ng-if="myForm.myName.$touched">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>
</form>

簡直是第二次解放啊。。。
form-touched

2.動態生成的表單的驗證

如果你有一部分form的內容是動態生成的,數量和名字都不確定的時候,該如何驗證這些生成的元素呢?其實維護一個動態的form本來就是個問題。但是在angular中,只需要記住一點:准備好你的數據,其他的交給angular。像下面這個例子,你只需要維護好一個數組,然后利用ng-repeat就可以快速的呈現到頁面上。
dynamic-form2
dynamic-form1

其實動態的form和一般的form驗證都是一致的,只是動態的form需要使用myForm[inout_name].$error的形式訪問

    <!-- 動態顯示狀態的負責人 -->
    <div class="form-group col-md-6" ng-repeat="sta in task.status_table | orderBy : sta.sequence_order">
        <label>{{sta.status_name}} 負責人</label>
        <select required class="form-control" ng-model="sta.user_id" ng-options="qa.id as qa.last_name+' '+qa.last_name for qa in taskUserList" name="{{sta.status_name}}">
        </select>
        <div ng-messages="newTaskForm[sta.status_name].$error" ng-if="newTaskForm.$submitted || newTaskForm[sta.status_name].$touched">
            <p class="error" ng-message="required">*請選擇負責人</p>
        </div>
    </div>

3. 必填項加亮顯示

有些表單我們不希望粗暴的在下面添加文字信息提示驗證,而是希望更簡潔的方式,如:加亮邊框,突出顯示
warn-validate
需要做的只是在required驗證沒通過的時候添加class,改變元素的樣式即可

        <form name="loginForm" novalidate ng-submit="loginPost()" class="navbar-form navbar-right" ng-hide="login">
            <fake-autocomplete></fake-autocomplete>
            <div class="form-group">
                <input name="user_name" required maxlength="50" type="text" class="form-control" placeholder="手機號或郵箱" ng-model="account.user_name" ng-class="{warn:loginForm.$submitted && loginForm.user_name.$error.required}">
            </div>
            <div class="form-group">
                <input name="password" required type="password" maxlength="50" placeholder="密碼" ng-model="account.password" ng-class="{'form-control':1,warn:loginForm.$submitted && loginForm.password.$error.required}">
            </div>
            <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-lock"></span> 登錄</button>
        </form>
.warn {
    border-color: #f78d8d !important;
    outline: 0 !important;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgb(239, 154, 154) !important;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(239, 154, 154) !important;
}

4. HTML5的驗證屬性

其實上面用到的這些個屬性都是html5提供的,詳細的看下面的文章
http://blog.csdn.net/sh_king/article/details/48713949
http://www.tuicool.com/articles/RjQZzm

1.輸入型控件

Input type

用途

說明

email

電子郵件地址文本框

 

url

網頁URL文本框

 

number

數值的輸入域

屬性 值 描述

max number 規定允許的最大值

min number 規定允許的最小值

step number 規定合法的數字間隔(如果 step="3",則合法的數是 -3,0,3,6 等)

value number 規定默認值

range

特定值的范圍的數值,以滑動條顯示

屬性 值 描述

max number 規定允許的最大值

min number 規定允許的最小值

step number 規定合法的數字間隔(如果 step="3",則合法的數是 -3,0,3,6 等)

value number 規定默認值

Date pickers

日期,時間選擇器

僅Opera9+支持,包含date, month, week, time, datetime, datetime-local

search

用於搜索引擎,比如在站點頂部顯示的搜索框

與普通文本框用法一樣,只不過這樣更語文化

color

顏色選擇器

僅Opera支持

2.表單驗證

名稱

用途

用法

valueMissing

確保控件中的值已填寫

將required屬性設為true,

<input type="text"required="required"/>

typeMismatch

確保控件值與預期類型相匹配

<input type="email"/>

patternMismatch

根據pattern的正則表達式判斷輸入是否為合法格式

<input type="text" pattern="[0-9]{12}"/>

toolong

避免輸入過多字符

設置maxLength,<textarea id="notes" name="notes" maxLength="100"></textarea>

rangeUnderflow

限制數值控件的最小值

設置min,<input type="number" min="0" value="20"/>

rangeOverflow

限制數值控件的最大值

設置max,<input type="number" max="100" value="20"/>

stepMismatch

確保輸入值符合min,max,step的設置

設置max min step,<input type="number" min="0" max="100" step="10" value ="20"/>

customError

處理應用代碼明確設置能計算產生錯誤

例如驗證兩次輸入的密碼是否一致,等會DEMO細說


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM