2014-09-05 35 views
0

我正在學習過去4天內的angular JS,現在我想進行組件驗證,比如有效的電子郵件,只有字符只有integer。這種驗證支持jquery.My問題是否角js也提供了這種驗證,或者我必須使用任何API或HTML5支持的任何驗證API。如何在Angular JS或HTML5中進行組件驗證

問候

+0

http://scotch.io/tutorials/javascript/angularjs-form-validation Angular JS Form Validati上 – 2014-09-05 05:15:35

回答

0

角支持上的曝光,你可以結合或檢查有效性範圍驗證模型驗證。

角度驗證

假設你有一個表格,你給它一個名字:

<form name="myForm"> 

角使用這個名字綁定的範圍稱爲myForm的典範。

在這種情況下,它是

$scope.myForm 

驗證模型也有,你可以結合或驗證對以下驗證屬性。

$scope.myForm.$valid // form is valid? 
$scope.myForm.$invalid // form is invalid? 
$scope.myForm.$pristine // is the form untouched? 
$scope.myForm.$dirty // is the form dirty? (opposite of $pristine) 
$scope.myForm.$error // this is a special error object that has validation flags 
         // that you can bind to as well. More on this later... 

例如,你可以在你的控制器使用這些特殊屬性:

app.controller('ctrl', function($scope) { 
    if($scope.myForm.$valid) { 
     // submit form... 
    } 
}); 

或者將它們綁定錯誤在你的HTML郵件:

<div ng-show="myForm.$invalid">Something is wrong!!</div> 

還有支持驗證表單中的字段。與表單驗證模型一樣,輸入驗證模型也具有相同的屬性。

把輸入文本字段的表單元素中,並給它一個名字:

<form name="myForm"> 
    <input name="myField" type="text" ng-model="name" /> 
</form> 

的名字是很重要的。該名稱用於在表單模型上定義屬性。在這種情況下,它是

$scope.myForm.myField 

像表單驗證對象,現場驗證對象也具有相同的驗證屬性:

$scope.myForm.myField.$valid // form is valid? 
$scope.myForm.myField.$invalid // form is invalid? 
$scope.myForm.myField.$pristine // is the form untouched? 
$scope.myForm.myField.$dirty // is the form dirty? (opposite of $pristine) 
$scope.myForm.myField.$error // this is a special error object that has validation flags 
           // that you can bind to as well. More on this later... 

$有效,$無效,$原始和$髒的布爾標誌。

但是,$ error對象是特殊的。它是驗證標誌的容器,可以通過角度指令或您創建的自定義指令自動設置。

例如,您可以添加一個需要驗證指令到現場與NG-模型:

<input type="text" ng-model="myField" required /> 

需要驗證指令將設置$錯誤的需要有效性標誌時字段爲空。

例如,

$scope.myForm.myField.$error.required 

這使您可以綁定到你的HTML相應的錯誤信息:

<div ng-show="myForm.myField.$error.required"> This field cannot be blank!</div> 

這就是角驗證簡而言之,

希望這是有幫助