Form validation using Angular JS
by sravikiran
HTML
<script src="<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">"></script>
<div ng-app="shopping">
<div ng-controller="ShoppingCartCtrl">
<form novalidate name="itemForm">
<table>
<tr>
<td>Name: </td>
<td><input name="name" type="text" ng-model="item.Name" required ng-pattern="name" /></td>
</tr>
<tr>
<td>Price: </td>
<td><input name="price" type="text" ng-model="item.Price" required valid-price /></td>
</tr>
<tr>
<td>Quantity: </td>
<td><input name="quantity" type="number" ng-model="item.Quantity" min="1" max="90" ng-pattern="integerval" required /></td>
</tr>
<tr>
<td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" /> </td>
</tr>
</table>
</form>
<div id="errMessages" class="errors">
<ul>
<li ng-repeat="message in failedValidations">{{message}}</li>
</ul>
</div>
</div>
</div>
CSS
.bold { font-weight:bold; }
table td{
padding: 10px;
}
table th{
font-weight: bold;
text-align: center;
}
span[ng-show]{
color: #FA787E;
}
.errors{
color: #FA787E;
}
JavaScript
angular.module('shopping',[])
.directive('validPrice',function(){
return{
require: "ngModel",
link: function(scope, elm, attrs, ctrl){
var regex=/^\d{2,4}(\.\d{1,2})?$/;
ctrl.$parsers.unshift(function(viewValue){
var floatValue = parseFloat(viewValue);
if( floatValue >= 50 && floatValue <=5000 && regex.test(viewValue)){
ctrl.$setValidity('validPrice',true);
//return viewValue;
}
else{
ctrl.$setValidity('validPrice',false);
}
return viewValue;
});
}
};
});
function ShoppingCartCtrl($scope, $window) {
$scope.item = {};
var errorMessages={
name:function(){
required="Name cannot be left blank";
pattern="Name cannot contain numbers or special characters";
return{
required: required,
pattern: pattern
};
}(),
price:function(){
required= "Price cannot be blank";
validPrice="Price should be a number between 50 and 5000 with maximum 2 digits after decimal point";
return{
required: required,
validPrice:validPrice
}
}(),
quantity:function(){
required="Quantity cannot be blank";
validQuantity="Quantity should be an integer between 1 and 90";
return{
required: required,
min: validQuantity,
max: validQuantity,
pattern: validQuantity
}
}()
};
$scope.failedValidations = [];
$scope.addItem = function(item) {
$scope.failedValidations = [];
errorMessage="";
if($scope.itemForm.$dirty && $scope.itemForm.$invalid){
for(validations in...