Validate repeated forms
Description
The following code shows how to validate form input element created by ng-repeat.
Example
<!doctype html>
<html ng-app="myApp" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script>
var app = angular.module('myApp', []);
<!-- w w w. j a va 2 s. c o m-->
app.controller('MainCtrl', function($scope) {
$scope.showError = function(ngModelController, error) {
return ngModelController.$error[error];
};
$scope.user = {
websites: [{url: 'http://www.example.com'}, {url: 'http://www.java2s.com'}]
};
$scope.remove = function(index) {
$scope.user.websites.splice(index, 1);
};
$scope.add = function() {
$scope.user.websites.push({ url: ''});
};
});
</script>
</head>
<body>
<form novalidate ng-controller="MainCtrl" name="userForm">
<div ng-show="userForm.$invalid">The User Form is invalid.</div>
<div class="control-group" ng-repeat="website in user.websites" ng-form="websiteForm">
<span class="input-append">
<input type="url" name="website" ng-model="website.url" required>
<button class="btn" ng-click="remove($index)">X</button>
</span>
<span ng-show="showError(websiteForm.website, 'url')" class="help-inline">You must enter a valid url (including http://)</span>
<span ng-show="showError(websiteForm.website, 'required')" class="help-inline">This field is required</span>
</div>
<button class="btn btn-small" ng-click="add()">Add Website</button>
<pre>{{user | json}}</pre>
</form>
</body>
</html>