I am completely New to Angularjs and trying to validate 2 scenarios. I have 2 text boxes one with start date and the other with end date. I am checking
I tried the below code which did not work. Any suggestions please.
Html Code
<label for="endDate" class="control-label">Start Date:</label>
<div>
<input type="text" class="form-control"
id="startDate" ng-model="startDate" />
</div>
<label for="text" class="control-label">End Date:</label>
<div>
<input type="text" class="form-control"
id="endDate" ng-model="endDate"
ng-change='checkErr(startDate,endDate)' />
</div>
<span>{{errMessage}}</span>
js code
$scope.checkErr = function(startDate,endDate){
$scope.errMessage = '';
$scope.curDate = new Date();
if(startDate < endDate){
$scope.errMessage = 'End Date should be greate than start date';
return false;
}
if(startDate < curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
You have the logic reversed on the first bit and you have to construct a new date from startDate to compare to today's date. Also you set curDate to the scope, $scope.curDate = new Date()
but then you were referencing it as curDate
without the $scope
so it was undefined. Lastly, you need to cast stateDate
and endDate
to a date as well. Otherwise you're just comparing strings.
$scope.checkErr = function(startDate,endDate) {
$scope.errMessage = '';
var curDate = new Date();
if(new Date(startDate) > new Date(endDate)){
$scope.errMessage = 'End Date should be greater than start date';
return false;
}
if(new Date(startDate) < curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
Working example: http://jsfiddle.net/peceLm14/
It looks like you're referencing curDate
which is undefined. Change the conditional to if (startDate < $scope.curDate)
. See fiddle for working example http://jsfiddle.net/4ec3atzk/1/
$scope.checkErr = function(startDate,endDate){
$scope.errMessage = '';
$scope.curDate = new Date();
if (startDate < endDate){
$scope.errMessage = 'End Date should be greate than start date';
return false;
}
if (new Date(startDate) < $scope.curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With