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
Show validation error on UI if start date is not greater than or equal to today. It should be today or any day after today.
Show validation error on UI if start date is greater than end date. End date should be greater than start date.
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;
}
};
I have input type as text for both date controls.I am using bootstrap date picker.
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;
}
};
$scope.datepickerObjectfromdates = {
todayLabel: 'Today',
closeLabel: 'Close',
setLabel: 'Ok',
setButtonType : 'button-calm',
todayButtonType : 'button-calm',
closeButtonType : 'button-calm',
inputDate: new Date(),
mondayFirst: true,
templateType: 'popup',
showTodayButton: 'true',
modalHeaderColor: 'bar-calm',
modalFooterColor: 'bar-calm',
callback: function (val) {
var getdate = GetFormattedFromDates(val);
$scope.date.FromDates = getdate;
localStorage.date = $scope.FromDates;
},
dateFormat: 'MM-dd-yyyy', //Optional
closeOnSelect: false, //Optional
};
function GetFormattedFromDates(val) {
if(typeof(val)==='undefined')
{
$scope.date.FromDates = '';
}
else {
var todayTime = new Date(val);
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
var year = todayTime.getFullYear();
return day + "/" + month + "/" + year;
}
}
$scope.datepickerObjecttodates = {
todayLabel: 'Today',
closeLabel: 'Close',
setLabel: 'Ok',
setButtonType : 'button-calm',
todayButtonType : 'button-calm',
closeButtonType : 'button-calm',
inputDate: new Date(),
mondayFirst: true,
templateType: 'popup',
allowOldDates: false,
showTodayButton: 'true',
modalHeaderColor: 'bar-calm',
modalFooterColor: 'bar-calm',
callback: function (val) {
var getdate = GetFormattedToDates(val);
$scope.date.ToDates = getdate;
//$scope.date.ToDates = getdate.clear();
},
dateFormat: 'dd-MM-yyyy', //Optional
closeOnSelect: false, //Optional
};
function GetFormattedToDates(val) {
if (typeof(val) === 'undefined') {
$scope.ToDates = '';
}
else {
var todayTime = new Date(val);
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var year = todayTime.getFullYear();
return day + "/" + month + "/" + year;
}
}
Related
I have written a javascript condition for checking the date condition.
What my requirement is, I have two textbox in which I add the dates, And what I want to check is that.
My both the dates which are entered into the textbox should not be greater than Current date.
I have tried the below code but it is accepting the date which is greater than system date.
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
var todayDateText = todayMonth + "/" + todayDay + "/" + todayYear;
var Dt1 = document.getElementById('txtFormDt').value;
var Dt2 = document.getElementById('txtToDt').value;
if (todayDateText > Dt1)
{
alert("System Date Should be grater than From Date");
}
if (todayDateText > Dt2) {
alert("System Date Should be grater than To Date");
}
if (Dt2 < Dt1) {
alert("To Date Should be grater than From Date");
return false;
}
return true;
}
You can compare Date objects directly using the <, >, >= and <= operators but not == or === since Dates are also Objects. However, make sure you correctly parse the values from the inputs, e.g.
function checkDate(el) {
var form = el.form;
var now = new Date();
var date = parseMDY(form.startDate.value);
form.parsedDate.value = date;
if (!date || isNaN(+date)) {
form.result.value = "Invalid date";
} else {
form.result.value = date < now;
}
}
// Parse string in m/d/y format
// Returns invalid date if month or day out of range
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
<form id="f0">
Insert date (m/d/y)<input type="text" name="startDate">
<input type="button" onclick="console.log(checkDate(this));" value="Check date">
<br>
Input date: <input name="parsedDate" readonly size="50">
<br>
Before today?<input name="result">
</form>
Sorry for posting this simple question. Application is going to be deployed soon, and recently a bug came, but i am not able to figure out why it is comming.
Created A JS_BIN this is the link
http://jsbin.com/razufavuru/1/edit?html,js,output
Error is minDate: 0 is disabling today's date also while i want to disable only past dates.
This is jquery code:
$("#leaveEndDate").datepicker(
{
minDate: 0,
beforeShowDay : disablePublicHolidaysAndWeekends,
minDate : dateToday,
onSelect : function(dateText, inst) {
var firstDate = $("#leaveStartDate").datepicker('getDate');
var selDate = null;
selDate = $(this).datepicker('getDate');
var lastDate = selDate;
if (lastDate < firstDate) {
$("#leaveEndDate").val('');
$("#endDateError").html(
"End Date must be greater than Start Date");
$(inst).datepicker('show');
} else {
$("#endDateError").html("");
calculateDays(firstDate, lastDate);
}
}
});
Disable Holiday and Weekends Method is
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
var getdate = year+ '/' + '0' +(month + 1) + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
if ($.inArray( getdate ,publicHolidayDates) != -1 || new Date() > date) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
this is the img
public holidays are comming from database.
It confuse me lot when this code for another datapicker works.
$("#targetDate").datepicker({
beforeShowDay : $.datepicker.noWeekends,
minDate : 0
});
Here it do not disable today date.
this is the img
jQuery Datepicker value minDate expect value of type
Type: Date or Number or String
Try minDate: new Date() instead, or minDate: '0'
UPDATE:
What causes your issue is your custom function:
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
if(month < 9 && month > 0){ //added control over month, as you would have got errors for month=10, 11, 12 in the below variable getdate
month = '0' +(month + 1);
}
else{
month += 1;
}
var getdate = year+ '/' + month + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
//removed "|| new Date() > date"
if ($.inArray( getdate ,publicHolidayDates) !== -1 ) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
Read this about Date comparison in javascript
Fiddle here
I'm trying to check if a date (from a date input) is different than today :
<input type="date" id="date">
Here my JS :
var selectedDate = document.getElementById('date');
var now = new Date();
if (selectedDate < now) {
alert("Some alert!");
return;
}
It doesn't work - any idea why ?
Thanks
Here the solution :
var selectedDate = document.getElementById('date').value;
var date = new Date(selectedDate);
var now = new Date();
if (date < now) {
alert("You picked an invalid date!");
return;
}
I have some problem with hiding days in datepicker depending of day of week e.g. if today is friday hide saturday and if today is saturday - hide sunday.
I have this code who check what day is today:
$(function () {
var day_date = new Date();
var weekday = new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[day_date.getDay()];
$('#day_of_week').val(n);
});
I also have this code to hide (but whole) weekends and days who always be hidden:
var disabledDays = ['15/8/2012', '1/11/2012', '11/11/2012', '25/12/2012', '26/12/2012'];
function nationalDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray(d + '/' + (m + 1) + '/' + y, disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
On datepicker the line who "execute" above code looks like this:
beforeShowDay: noWeekendsOrHolidays,
I try to do this with this code, but it didn't work:
$('#day_of_week').change(function()
if( $("#day_of_week").val() == Friday ) {
$("#date_from, #date_to").datepicker({
beforeShowDay: noWeekendsOrHolidays
});
}
else {
}
});
I will be very grateful for any help.
I am using a date picker in which it automatically work on hiding date.
I hope it will helpful to you.
http://multidatespickr.sourceforge.net/#maxPicks-demo
I got a link regarding this and hopefull it will work.
http://multidatespickr.sourceforge.net
I wonder how to set next month with showing only mondays active:
i tried to do smth like that but it wont work
function onlyMondaysNextMonth(date){
var day = date.getDay();
var mDate = date.getMonth() + 1;
return {
minDate: mDate,
}
return [(day == 1),''];
}
Thank you.
Use the following code to enable only Mondays starting from next month
var minDate = null;
var now = new Date();
if (now.getMonth() == 11) {
minDate = new Date(now.getFullYear() + 1, 0, 1);
} else {
minDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
/* create datepicker */
jQuery(document).ready(function () {
jQuery('#datepicker').datepicker({
minDate: minDate,
constrainInput: true,
beforeShowDay: beforeShowDay
});
});
function beforeShowDay(date) {
var day = date.getDay();
if (day == 1)
return [true]
return [false];
}
The working sample is hosted in http://elangovanr.com/samples/jquery/datepickermonday.html for your reference.