Hi I am working on a project where I date field.
I need to have validation for the same field.
1) Should allow user to select previous dates or year. 2) But not allow user to select future date.
I have used the below code and it works fine for only present year. Can anyone help me to achive it.
$scope.$watch('date', function(val) {
var dateNewOnCreatessssss = $scope.convertedTimeToSend(new Date());
console.log("dateNewOnCreatessssss", dateNewOnCreatessssss);
$scope.convertedTimeToSend = function(timestamp) {
var c = moment(timestamp).format("MM-DD-YYYY");
return c;
};
if (val) {
$scope.dateErrorMsg = false;
}
var dateNewOnCreatessssssll = $scope.convertedTimeToSend(val);
console.log("dateNewOnCreatessssssll", dateNewOnCreatessssssll);
if (dateNewOnCreatessssssll > dateNewOnCreatessssss) {
$scope.dateErrorMsgsssssss = true;
$scope.newReceiptSaveBtn = "true";
} else {
$scope.dateErrorMsgsssssss = false;
$scope.newReceiptSaveBtn = "false";
}
});
Well m8, your code is a big mess. Just use all the good stuff provided by momentjs to make it work. Finaly this function should look like this simple snippet:
$scope.$watch('date', function(val) {
if (val) {
//Init
var today = new moment();
var selectedDate = new moment(val);
if(selectedDate.isBefore(today)){
$scope.dateErrorMsg = false;
$scope.newReceiptSaveBtn = "false";
} else {
$scope.dateErrorMsg = true;
$scope.newReceiptSaveBtn = "true";
}
}
});
While the example above is focusing a solution based on your codes it would be much better to create a pure AngularJS handling like in this approach:
var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function ($scope) { //Init $scope.date = new moment()._d; $scope.error = false; $scope.validateDate = function () { //Init var today = new moment(); var selectedDate = new moment($scope.date); if(selectedDate.isBefore(today)){ $scope.error = false; } else { $scope.error = true; } } });
.error { border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input type="date" ng-model="date" ng-change="validateDate()" ng-class="{ 'error': error }" /> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.