form表單驗證概述
-
novalidate -- 屏蔽瀏覽器對表單的默認驗證行為
-
ng-model -- 綁定的數據
-
ng-required -- 是否必填(可以控制是否是不填校驗)
-
required -- 必填(頁面加載的時候就會自動驗證 == true)
-
ng-minlength -- 最小長度
-
ng-maxlength -- 最大長度
-
ng-pattern -- 匹配模式(正則)
-
email -- 郵箱
-
url -- 網址
-
number -- 數字
-
ng-change -- 值變化的回調
在表單中控制變量
-
formName.inputField.$pristine 字段是否 未更改
-
formName.inputField.$dirty 字段是否 更改
-
formName.inputField.$valid 字段是否 有效
-
formName.inputField.$invalid 字段是否 無效
-
formName.inputField.$error 字段 錯誤信息
一些有用的CSS樣式
- ng-valid //有效時的樣式名
- ng-invalid //無效時的樣式名
- ng-pristine //未更改的樣式名
- ng-dirty //更改后的樣式名
- ng-submitted //提交后的樣式名.當用戶試圖提交表單時,可以在作用域中捕獲到一個submitted值,然后對表單內容進行驗證並顯示錯誤信息
例如:
input.ng-invalid {
border: 1px solid red;
}
input.ng-valid {
border: 1px solid green;
}
form表單示例

<!--注冊表單--> <form class="zhucezhuti" id="myForm" role="form" ng-app="validate" ng-controller="validateCtrl" name="myForm" ng-submit="submitFormRegiter(myForm.$valid,'Regiter','/UserCenter/UpdateUserMessage')" novalidate> <div class="mb-15 distab marcenter"> <input class="querenyong" type="email" id="UserEmail" data-value="1" name="UserEmail" placeholder="電子郵箱(用戶名)" ng-model="UserEmail" required> <span class="errorSty" ng-show="myForm.UserEmail.$dirty && myForm.UserEmail.$invalid && myForm.submitted"> <span ng-show="myForm.UserEmail.$error.required">*請輸入郵箱</span> <span ng-show="myForm.UserEmail.$error.email">*非法的郵箱地址。</span> </span> <span class="eSsuccess"></span> </div> <div class="mb-15 distab marcenter"> <div class="distab"> <input class="yanzhengma" type="number" id="emailYZM" name="yzm" placeholder="郵箱驗證碼" ng-model="yzm" required> <input class="huoquyan" type="button" id="btn" value="獲取郵箱驗證碼" ng-disabled="myForm.UserEmail.$invalid" onclick="time(this, 'SendMailMessage')" /> </div> <span class="errorSty" ng-show="myForm.yzm.$dirty && myForm.yzm.$invalid && myForm.submitted"> <span ng-show="myForm.yzm.$error.required">*請輸入驗證碼。</span> <span ng-show="myForm.yzm.$error.number">*請輸入正確的驗證碼。</span> </span> </div> <div class="mb-15 distab marcenter"> <input class="querenyong" type="password" name="password" id="password" placeholder="密碼(6-16個字符組成,區分大小寫)" ng-model="password" ng-minlength="6" ng-maxlength="16" required> <span class="errorSty" ng-show="myForm.password.$dirty && myForm.password.$invalid && myForm.submitted"> <span ng-show="myForm.password.$error.required">*密碼是必須的。</span> <span ng-show="myForm.password.$error.minlength">*密碼不少於6位。</span> <span ng-show="myForm.password.$error.maxlength">*密碼不多於16位。</span> </span> </div> <div class="mb-15 distab marcenter"> <input class="querenyong" type="password" name="confirmPassword" id="confirmPassword" placeholder="確認密碼" ng-model="confirmPassword" pw-check="password" required> <span class="errorSty" ng-show="myForm.confirmPassword.$dirty && myForm.confirmPassword.$invalid && myForm.submitted"> <span ng-show="myForm.confirmPassword.$error.required">*確認密碼必填。</span> <span ng-show="!myForm.confirmPassword.$pristine && myForm.confirmPassword.$invalid">*預設密碼和確認密碼不一致。</span> </span> </div> <div class="tiaokuan mb-15"> <input class="fuxuan" ng-model="Iagree" type="checkbox" required> <font class="yuedu">請務必仔細閱讀並同意 <a href="javascript:void(0)" onclick="showTanc('tanc','closethis')">網站使用條款</a> 和 <a href="javascript:void(0)" onclick="showTanc('tanc1','closethis')">電子金融交易使用條款 </a></font> <span class="errorSty" ng-show="myForm.Iagree.$invalid && myForm.submitted"> <span ng-show="myForm.Iagree.$error.required">*您未同意條款。</span> </span> </div> <input class="zhucedenglu" type="submit" value="注冊" ng-disabled="!myForm.$dirty"> </form>

var app = angular.module('validate', []); app.controller('validateCtrl', function ($scope) { //僅當submitted設置為true時,容納錯誤信息的div才會展示出來(即提交表單時顯示相應錯誤信息) $scope.submitted = false; $scope.submitFormRegiter = function (isValid, action, nextaction) { if (!isValid) { // alert('驗證失敗'); $scope.myForm.submitted = true; } else { $.get(action, { UserEmail: $("#UserEmail").val(), messageCode: $("#messageCode").val(), UserPassWord: $("#password").val() }, function (result) { if (result.ReState == true) { window.location.href = nextaction; } else { alert("操作失敗!");//完善信息頁面沒有返回提示信息。根據ReState顯示相應提示 } }); } }; })
如果想保留實時錯誤提示的體驗,可以在用戶從某個輸入字段失焦后提示錯誤信息:(添加一個自定義指令)

html代碼 <input ng-class="{error: signup_form.name.$dirty && signup_form.name.$invalid}" type="text" placeholder="Name" name="name" ng-model="signup.name" ng-minlength="3" ng-maxlength="20" required ng-focus /> js代碼 app.directive('ngFocus', [function() { var FOCUS_CLASS = "ng-focused"; return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$focused = false; element.bind('focus', function(evt) { element.addClass(FOCUS_CLASS); scope.$apply(function() { ctrl.$focused = true; }); }).bind('blur', function(evt) { element.removeClass(FOCUS_CLASS); scope.$apply(function() { ctrl.$focused = false; }); }); } }; }]); ngFocus指令給表單輸入字段的blur和focus添加了對應的行為,添加了一個名為ng-focused的類,並將$focused的值設置為true。接下來,可以根據表單是否具有焦點來展示獨立的錯誤信息。如下所示: <div class="error" ng-show="signup_form.name.$dirty && signup_form.name.$invalid && !signup_form.name.$focused">
在發布的Angularjs 1.3中,Angularjs核心做了一個升級。它不再需要基於一個詳細的表達式狀態創建元素顯示或隱藏。從1.3開始,Angularjs中新增了一個ngMessages指令
- 安裝:<script type="text/javascript" src="bower_components/angular-messages/angular-messages.js"></script>
- 告訴angularjs將ngMessage作為應用程序的依賴模塊引入:angular.module('myApp',['ngMessages']);
- 開始使用:<div class="error" ng-messages="signup_form.name.$error" ng-messages-include="templates/errors.html" ng-messages-multiple>
- 如果想要更新這個實現同時顯示所有的錯誤,只需在ng-message指令旁使用ng-messages-multiple屬性即可
- <!-- templates/errors.html內容 -->
- <div ng-message="required">This field is required</div>
- <div ng-message="minlength">The field must be at least 3 characters</div>
- <div ng-message="maxlength">The field cannot be longer than 20 characters</div>
- 為不同的字段自定義錯誤信息,可以在這個指令內簡單地插入一個自定義錯誤信息。由於ngMessages涉及ngMessages容器中錯誤列表的順序,可以通過在這個指令中列出自定義錯誤信息的方式覆蓋它們
ngMessages示例

<form name="signup_form" novalidate ng-submit="signupForm()" ng-controller="signupController" ensure-unique="/api/checkUsername.json"> <label> Your name </label> <input type="text" placeholder="Username" name="username" ng-model="signup.username" ng-minlength=3 ng-maxlength=20 required /> <div class="error" ng-messages="signup_form.username.$error"> <div ng-message="required"> Make sure you enter your username </div> <div ng-message="checkingAvailability"> Checking... </div> <div ng-message="usernameAvailablity"> The username has already been taken. Please choose another </div> </div> <button type="submit"> Submit </button> </form> 在這個用法中,我們檢查了錯誤信息的自定義屬性。為了添加自定義錯誤信息,將會把他們應用到自定義ensureUnique指令的ngModel中 app.directive('ensureUnique', function($http) { return { require: 'ngModel', link: function(scope, ele, attrs, ctrl) { var url = attrs.ensureUnique; ctrl.$parsers.push(function(val) { if (!val || val.length === 0) { return; } ngModel.$setValidity('checkingAvailability', true); ngModel.$setValidity('usernameAvailablity', false); $http({ method: 'GET', url: url, params: { username: val } }).success(function() { ngModel .$setValidity('checkingAvailability', false); ngModel .$setValidity('usernameAvailablity', true); })['catch'](function() { ngModel .$setValidity('checkingAvailability', false); ngModel .$setValidity('usernameAvailablity', false); }); return val; }) } } });