例子
<html ng-app="myApp">
<head>
<title>AngularJS Routing</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script src="http://code.angularjs.org/1.2.7/angular.js"></script>
<script src="http://code.angularjs.org/1.2.7/angular-route.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="MainCtrl">
<form name="form" >
Min: <input name="min" type="number" ng-model="field.min" lower-than="{{field.max}}" />
<span class="error" ng-show="form.min.$error.lowerThan">
Min cannot exceed max.
</span>
<br />
Max: <input name="max" type="number" ng-model="field.max" />
</form>
</body>
</html>
.error {
display: block;
font-size: 12px;
color: red;
}
'use strict';
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.field = {
min: 400,
max: 300
};
});
app.directive('lowerThan', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.lowerThan;
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('lowerThan', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) < parseInt(comparisonModel, 10) );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('lowerThan', function(comparisonModel){
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
常用的表單驗證指令
1. 必填項驗證
某個表單輸入是否已填寫,只要在輸入欄位元素上添加HTML5標記required即可:
<input type="text" required />
2. 最小長度
驗證表單輸入的文本長度是否大於某個最小值,在輸入欄位上使用指令ng-minleng= "{number}":
<input type="text" ng-minlength="5" />
3. 最大長度
驗證表單輸入的文本長度是否小於或等於某個最大值,在輸入欄位上使用指令ng-maxlength="{number}":
<input type="text" ng-maxlength="20" />
4. 模式比對
使用ng-pattern="/PATTERN/"來確保輸入能夠匹配指定的Regex:
<input type="text" ng-pattern="/[a-zA-Z]/" />
5. 電子郵件
驗證輸入內容是否是電子郵件,只要像下面這樣將input的類型設定為email即可:
<input type="email" name="email" ng-model="user.email" />
6. 數字
驗證輸入內容是否是數字,將input的類型設定為number:
<input type="number" name="age" ng-model="user.age" />
7. URL
驗證輸入內容是否是URL,將input的類型設定為 url:
<input type="url" name="homepage" ng-model="user.facebook_url" />