Reputation: 341
I have a small Angular validation where I want an error to show if input has less than 3 charecters, or more than 6 charecters.
For what I have done, error is shown only when I start typing on the input, not otherwise, for example; if I load page and definitely on page load the input charecters are less than 3, so it should show error, but it shows error only when i start typing on input.
my html:
<form name="someform">
<input type="text" ng-model="handle"/>
<div ng-if="handle.length<lowcharec" class="alert" style="color: red">sorry, maxlength cannot be less than 3
</div>
<div ng-if="handle.length>highcharec" class="alert" ng-init="highcharec" style="color: red">sorry, maxlength cannot be greater than 6
</div>
<input type="submit"/>
</form>
my script:
$scope.lowcharec = 3;
$scope.highcharec = 6;
I mam missing something and am new to angular, pls guide what i am doing wrong.
Upvotes: 0
Views: 1427
Reputation: 4490
You are not showing complete code. So it is not easy to figure what is your actual problem. Here you can see a working example.
var app = angular.module('app', []);
app.controller('FormCtrl', function($scope) {
$scope.handle = '';
$scope.lowcharec = 3;
$scope.highcharec = 6;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<form name="someform" ng-controller="FormCtrl">
<input type="text" ng-model="handle" />
<div ng-if="handle.length < lowcharec" class="alert" style="color: red">sorry, maxlength cannot be less than 3
</div>
<div ng-if="handle.length > highcharec" class="alert" ng-init="highcharec" style="color: red">sorry, maxlength cannot be greater than 6
</div>
<input type="submit" />
</form>
</body>
Upvotes: 0
Reputation: 934
That's because your handle
variable is still undefined when the page loads (and remains so until you start typing in it), and undefined < 3
evaluates to false. To fix this change your ng-if to ng-if="handle.length<lowcharec || !handle"
.
Upvotes: 1