Float validation using Angular JS
HTML
<script src="<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">"></script>
<div ng-app="float-input">
<div ng-controller="FloatCtrl">
<form novalidate name="itemForm">
<h4>Float validation using Angular JS</h4>
<div>
Float input:
<input name="price" type="text" ng-model="item.Float" required smart-float />
</div>
<div>
{{item.Float}}
</div>
</form>
<div ng-show="itemForm.name.$dirty && itemForm.name.$invalid">
<span ng-show="itemForm.name.$error.required">Name cannot be left blank</span>
<span ng-show="itemForm.name.$error.pattern">Name cannot contain numbers or special characters</span>
</div>
<div ng-show="itemForm.price.$dirty && itemForm.price.$invalid">
<span ng-show="itemForm.price.$error.required">Price cannot be blank</span>
<span ng-show="itemForm.price.$error.validFloat">* value should be a number between 0 and 100 with maximum 2 digits after decimal point</span>
</div>
</div>
</div>
CSS
.bold { font-weight:bold; }
table td{
padding: 10px;
}
table th{
font-weight: bold;
text-align: center;
}
input.ng-invalid.ng-dirty {
background-color: #FA787E;
}
input.ng-valid.ng-dirty {
background-color: #78FA89;
}
span[ng-show]{
color: #FA787E;
}
JavaScript
angular.module('float-input',[])
.directive('smartFloat',function(){
return{
require: "ngModel",
link: function(scope, elm, attrs, ctrl){
var regex=/^\d{1,5}([\.,](\d{1,5})?)?$/;
ctrl.$parsers.unshift(function(viewValue){
if( regex.test(viewValue)){
var floatValue = viewValue.replace(',','.');
floatValue = parseFloat(floatValue);
if(floatValue >= 0 && floatValue <=100) {
ctrl.$setValidity('validFloat',true);
return parseFloat(floatValue);
}
else {
ctrl.$setValidity('validFloat',false);
}
}
else{
ctrl.$setValidity('validFloat',false);
}
return viewValue;
});
}
};
});
function FloatCtrl($scope, $window) {
$scope.item = {};
$scope.addItem = function(item) {
errorMessage="";
if($scope.itemForm.name.$dirty && $scope.itemForm.name.$invalid)
{
if($scope.itemForm.name.$error.required)
errorMessage=errorMessage+"Name is required.";
}
$window.alert(errorMessage);
$scope.itemForm.$setPristine();
};
}