[AngularJS] AngularJS系列(3) 中級篇之表單驗證

来源:http://www.cnblogs.com/neverc/archive/2016/09/28/5912340.html
-Advertisement-
Play Games

目錄 基本驗證 驗證插件messages 自定義驗證 基本驗證 以上展示了基本的ng驗證. 這裡重點介紹一下上面的特例: novalidate: 禁用H5自帶的驗證 ng-maxlength: 如果不寫ng,maxlength則直接限制最多輸入字元,稍微有點區別(IE9 + Chrome 測試) n ...


目錄

 

基本驗證

    <form name="form" novalidate ng-app>
        <span>{{form.$invalid}}</span>
        <span>{{form.$valid}}</span>
        <span>{{form.$dirty}}</span>
        <span>{{form.$pristine}}</span>
        <input type="text" ng-model="user" required />
        <input type="text" ng-model="pwd" required minlength="4" ng-maxlength="5" />
        <input type="text" ng-model="phone" required ng-pattern="/1[3|5|7|8|][0-9]{9}/" />
        <input type="email" ng-model="email" required />
        <input type="url" ng-model="url" required />
        <input type="number" ng-model="number" required />
        <div>
            <button type="reset" ng-disabled="form.$pristine">重置</button>
            <button type="submit" ng-disabled="form.$invalid">提交</button>
        </div>
    </form>

以上展示了基本的ng驗證.

這裡重點介紹一下上面的特例:

novalidate:   禁用H5自帶的驗證

ng-maxlength: 如果不寫ng,maxlength則直接限制最多輸入字元,稍微有點區別(IE9 + Chrome 測試)

ng-pattern:  通過正則驗證,如果不寫ng開頭,無驗證效果.

註:要啟用驗證 同時需要綁定一個ng-model

 

屬性類   描述
$valid ng-valid Boolean 告訴我們這一項當前基於你設定的規則是否驗證通過
$invalid ng-invalid Boolean 告訴我們這一項當前基於你設定的規則是否驗證未通過
$pristine ng-pristine Boolean 如果表單或者輸入框沒有使用則為True
$dirty ng-dirty Boolean 如果表單或者輸入框有使用到則為True

訪問表單屬性

  • 方位表單: <form name>.<angular property>

  • 訪問一個輸入框: <form name>.<input name>.<angular property>

 

 

驗證插件

在介紹messages插件之前,我們看下本來的驗證提示

    <form name="form" ng-app novalidate>
        <span>{{form.user.$error.required?'user該項必填':''}}</span>
        <input type="text" ng-model="user" name="user" required />
        <span>{{form.pwd.$error.required?'pwd該項必填':''}}</span>
        <input type="text" ng-model="pwd" name="pwd" required />
        <span>{{form.info.$error.required?'info該項必填':''}}</span>
        <input type="text" ng-model="info" name="info" required />
        <span>{{form.age.$error.required?'age該項必填':''}}</span>
        <input type="text" ng-model="age" name="age" required />
        <div>
            <button type="submit" ng-disabled="form.$invalid">提交</button>
        </div>
    </form>

這裡只是判斷了require 當我們的代碼 我們重覆寫了很多3元表達式

 

messages插件就是更友好的解決重覆的問題

    <form name="form" ng-app="myApp" novalidate>
        <input type="email" ng-model="user" name="username" required minlength="4" />
        <div ng-messages="form.username.$error" ng-messages-multiple>
            <div ng-message="required">該項必填</div>
            <div ng-message="minlength">低於最低長度</div>
            <div ng-message="email">應為email</div>
        </div>
    </form>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-messages.min.js"></script>
    <script>
        angular.module('myApp', ['ngMessages']);
    </script>

Nuget:Install-Package AngularJS.Messages 

 

自定義驗證

通過基本的驗證方式,我們已經能夠解決大部分的驗證問題.但項目中永遠充滿著各種各樣的需求.

在ng中的自定義驗證,一般通過指令的形式創建.

    <form name="form" ng-app="myApp" novalidate>
        <input type="email" ng-model="user" name="username" required ensure-unique minlength="4" />
        <div ng-messages="form.username.$error" ng-messages-multiple>
            <div ng-message="required">該項必填</div>
            <div ng-message="minlength">低於最低長度</div>
            <div ng-message="email">應為email</div>
            <div ng-message="unique">用戶名已存在</div>
        </div>
    </form>

在上面的messages插件Demo中,新建一行驗證用戶名已存在 以及 在input上添加了ensure-unique指令

同時,我們需要在js中定義ensure-unique指令:

angular.module('myApp', ['ngMessages']).directive('ensureUnique', ['$http', '$timeout', '$window', function ($http, $timeout, $window) {
            return {
                restrict: "A",
                require: 'ngModel',
                link: function (scope, ele, attrs, ngModelController) {
                    scope.$watch(attrs.ngModel, function (n) {
                        if (!n) return;
                        $timeout.cancel($window.timer);
                        $window.timer = $timeout(function () {
                            $http({
                                method: 'get',
                                url: '/api/checkusername/', //根據換成自己的url
                                params: {
                                    "username": n
                                }
                            }).success(function (data) {
                                ngModelController.$setValidity('unique', data.isUnique); //這個取決於你返回的,其實就是返回一個是否正確的欄位,具體的這塊可以自己修改根據自己的項目
                            }).error(function (data) {
                                ngModelController.$setValidity('unique', false);
                            });
                        }, 500);
                    });
                }
            };
        }]);

指令不是本節重點內容,這裡簡單說下

ngModelController.$setValidity('unique', bool);

通過該API可以設置$error.unique.

setValidity為true,則$error.unique為false

 

本文地址:http://www.cnblogs.com/neverc/p/5912340.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、浮動導航條 ...
  • ...
  • 使用 @ 定義變數變數可以做運算@color : #000;@width : 1000px;使用 & 表示當前類.box{&:hover{color : #000;}}css 可以嵌套ul{display : block;li{float : left;a{font-size : 18px;}}}繼 ...
  • 系列文章 -- ES6筆記系列 很久很久以前,在做Node.js聊天室,使用MongoDB數據服務的時候就遇到了多重回調嵌套導致代碼混亂的問題。 JS非同步編程有利有弊,Promise的出現,改善了這一格局,讓非同步編程表現出類似“同步式代碼”的形式,更好地體現了它的價值。 一、基本概念 1. Prom ...
  • 今天看到一篇文章關於清除浮動的,突然間腦袋短路了,咦?為什麼要清除浮動?原諒我的無知,搜了下原來是這樣,又倒騰出原來的筆記,唉,本來就有記錄啊,而且也會經常用到,用的久了連原理都忘了。恩,防止自己再犯同樣的錯誤,我還是自己總結整理出來吧!話不多說,代碼為證! 恩,各個瀏覽器運行的效果圖如下: 其中A ...
  • 封裝Encapsulation 如下代碼,這就算是封裝了 (function (windows, undefined) { var i = 0;//相對外部環境來說,這裡的i就算是封裝了 })(window, undefined); 繼承Inheritance (function (windows, ...
  • 什麼是閉包?先看一段代碼: ? 1 2 3 4 5 6 7 8 9 10 function a(){ var n = 0; function inc() { n++; console.log(n); } inc(); inc(); } a(); //控制台輸出1,再輸出2 ? 1 2 3 4 5 6 ...
  • 1.工廠模式 缺點:①無法確定對象的類型(因為都是Object)。 ②創建的多個對象之間沒有關聯。 2.構造函數 缺點:①多個實例重覆創建方法,無法共用。 ②多個實例都有sayName方法,但均不是同一個Function的實例。 3.原型方法 缺點:①無法傳入參數,不能初始化屬性值。 ②如果包含引用 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...