How to restrict date and month not valid in Jquery / Javascript - javascript

This is my code
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="jqueryDate"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
<div style="font-family: Helvetica,Arial,sans-serif; font-size: 12px; line-height: 150%;">
<strong>HTML5 "date" input type:</strong> <input type="date" name="html5date"><br>
<strong>jQuery "date" input type mimic:</strong> <input type="text" name="jqueryDate" placeholder="dd/mm/yyyy"><br>
Key Input: <span id="keyP">null</span>
</div>
In the above code i have a textbox . In that textbox user enter date manually . It takes date format worked . But user enter day more than 31 and month 12 it not accept.How to restrict date and month by using Jquery or Javascript.
This is Jsfiddle :- https://jsfiddle.net/ChrisCoray/hLkjhsce/

You Need to add 'datePicker'as class name
$(".datePicker").datepicker({
dateFormat: 'd/mm/yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
minDate: Date.parse("1900-01-01"),
maxDate: Date.parse("2100-01-01"),
yearRange: "c-90:c+150"
});
// validation in case user types the date out of valid range from keyboard : To fix the bug with out of range date time while saving in sql
$(function () {
$.validator.addMethod(
"date",
function (value, element) {
var minDate = Date.parse("1900-01-01");
var maxDate = Date.parse("2100-01-01");
var valueEntered = Date.parse(value);
if (valueEntered < minDate || valueEntered > maxDate) {
return false;
}
return !/Invalid|NaN/.test(new Date(minDate));
},
"Please enter a valid date!"
);
});

Related

Datepicker ui - check if dates from/to overlapping disabled days

I have 2 datepickers - date from and date to, something like hotel reservation system. How do I check (and show hidden div.error) if there are some disabled days in selected period?
Ex. - selected dates - from 2021-12-20 to 2021-12-31; disabled days are ["2021-12-25", "2021-12-26"] -> show "error".
<div class="error" style="display:none">Sorry, but we have no available rooms in selected dates.</div>
<script>
$( function() {
var disableddates = ["2021-12-25", "2021-12-26"];
$.datepicker.setDefaults($.datepicker.regional["de"]);
$( "#from" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [ disableddates.indexOf(string) == -1 ]
}
});
$( "#to" ).datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate("yy-mm-dd", date);
return [disableddates.indexOf(string) == -1 ]
}
});
});
</script>

jQuery finding descendant by ID not working

I'm trying to change the value of a jQuery datepicker input element in a form to the first date in the week of the user-selected date once the submit button is clicked but before the form is actually submitted.
I'm finding that the following Javascript works (using a class selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find('.week-picker').datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
startDate is a Date object.
But this code does not work (using an ID selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find("#week-picker").datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
console.log($(this).closest('form').find(".week-picker").datepicker( "setDate", startDate ).val()); produces a proper date, like 06/27/2018.
console.log($(this).closest( 'form' ).find('#week-picker').val()); produces undefined.
Why is this happening? Isn't an ID a valid selector?
HTML:
<form action="/checkin" method="post">
<div class="form-group row mb-2">
<div class="col-md-6 offset-md-3">
<input class="week-picker form-control" type="text" id="week-picker" name="week_start" placeholder="Select week" style="opacity: 0;position: absolute;">
</div>
</div>
<div class="form-group row mt-4">
<div class="col">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
The datepicker portion of my JS:
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$(this).closest( 'form' ).find('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$(this).closest( 'form' ).find('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$(document).on( 'mousemove','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').addClass('ui-state-hover'); });
$(document).on('mouseleave','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').removeClass('ui-state-hover'); });
#week-picker is a valid selector, as long as your input has that ID assigned. What is happening in your case is that there is JS turning your input into a datepicker, and it changes the ID of the element when it loads. As you posted from your element inspector, your input no longer has the week-picker ID, it is now dp1529862475978.
This is not uncommon, and the behavior you're getting is the expected one. If you need to make sure that you're targeting this datepicker instead of another one with the same class, you can use the name attribute:
$("input[name='week_starting']")
You should never have 2 inputs with the same name on the same page, so it's as unique as an ID. The ID you're seeing in the element inspector is probably randomly generated, so you don't want to use that.

jQuery datepicker specific date disable is not working

I have code to disable specific dates on jquery datepicker. code runs fine on my local environment but not working on GoDaddy windows hosting
var disableddates = result; //result is array of dates ["1/7/2018","1/8/2018","1/9/2018"]
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay : DisableSpecificDates
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay : DisableSpecificDates
});
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('mm/dd/yy', date);
console.log(string); //this string return with leading zero 01/07/2018...
return [disableddates.indexOf(string) == -1];
}
This code run fine on local but when making it live it is not disabling specific dates in jQuery datepicker.
You do not need to format the date if it's already in a date format. For example, if result contains an array date like "1/7/2018", you can create a Date object from this:
var newDate = new Date(result[0]);
With this in mind, you can easily make and manipulate a Date. DatePicker passes a Date object to the function too. Here is a solution you might try:
$(function() {
var disableddates = ["1/7/2018", "1/8/2018", "1/9/2018"];
$("#txtFromdate, #txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: "m/d/yy"
});
$("#txtFromdate").change(function() {
$("#txtTodate").datepicker("option", "minDate", $(this).val());
});
function DisableSpecificDates(date) {
var result = [true];
$.each(disableddates, function(k, v) {
var exclude = new Date(v).toString();
var today = date.toString();
if (exclude == today) {
console.log("Match", exclude, today);
result = [false];
}
});
return result;
}
});
label {
width: 60px;
}
input {
width: 10em;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="txtFromdate">From:</label>
<input type="text" id="txtFromdate" />
<label for="txtTodate">To:</label>
<input type="text" id="txtTodate" />
My Testing done here: https://jsfiddle.net/95t81vzq/3/
Hope that helps.

datetimepicker is not working correctly

I have created one custom control for datetime picker in one control i have given three mode datetimepicker,timepicker and datepicker.For which i have created one property called CalenderMode of type enum which stores these three modes and which value i am given to the property according to that i am changing the datetimepicker,if i given timepicker then my timepicker is enabled,if i give datepicker then date picker is enabled and if i give datetimepicker then my datetimepicker is enabled this i am handling in jquery.
For validation of these i am given format from c# and that format i am using in client side but now problem is if my timepicker or date picker is enabled and from timepicker i am selecting time but in text box it showing date time this is same for the date picker also there also it is showing date time.
Here i am not understanding what is the issue.
My code of jquery where i am changing the mode of calender using assigning the value to property is
$(document).ready(function () {
$('.calendercssclass').each(function () {
var result;
var value = $(this).closest('.DateControl').find("input[type=hidden][id*='CalenderTypeModeID']").val();
if (value == "timepicker") {
$(this).datetimepicker({
timepicker: true,
datepicker: false
//mask: true
});
}
else if (value == "datepicker") {
$(this).datetimepicker({
timepicker: false,
datepicker: true
// mask: true
});
}
else {
$(this).datetimepicker({
//mask: true
});
}
});
});
To give the format for validation i am using following code
function ValidateFormatOfDatecontrol(sender, args) {
debugger;
args.IsValid = true;
var format;
$('.calendercssclass').each(function () {
var result;
var value = $(this).closest('.DateControl').find("input[type=hidden][id*='CalenderTypeModeID']").val();
if (value == "timepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientTimeFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
else if (value == "datepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientDateFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
else if (value == "datetimepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientDateTimeFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
});
}
server side code for giving format for validation is
this.clientDateFormat.Value = "MM/DD/YYYY";
this.clientDateTimeFormat.Value = "mm/dd/yyyy H:i A";
this.clientTimeFormat.Value = "H:i";
Screenshot for issue is
Can anybody help me for this?
Here You are using Rain Jquery so fromat of Rain for the time is different from the moment what you are using for the validation so following is the format for both
Rain Jquery Time Format : h:i A
Moment Time Format : h:mm A
Following is the sample code
Script
$(document).ready(function () {
$(".date").datetimepicker({
format: 'h:i A',
datepicker:false
});
$(".date").change(function () {
var format = "h:mm A";
$('#message').text(moment($(".date").val(), format, true).isValid());
});
});
Markup
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="date"></asp:TextBox>
<asp:Label ID="message" runat="server" CssClass="message"></asp:Label>
</div>

Two datetimepickers

I am using Bootstrap datetimepickers to input start and end datetimes.
Is there any way to make sure/validate that the end datetimepicker is not before the start datatimepicker?
$('#start').datetimepicker({
format: 'dd-mm-yyyy hh:ii',
autoclose: true,
startDate: date
})
$('#end').datetimepicker({
format: 'dd-mm-yyyy hh:ii',
autoclose: true,
startDate: date
})
i can suggest this instead of bootstrap, look here and just replace the min option
https://jqueryui.com/datepicker/#min-max
$('#DatePicker').datetimepicker({
timepicker : false,
format : 'd.m.Y',
minDate : '-1969/12/31'
})
You have to set a min date, it should be dinamically set that way it will work with different dates
I think you can check it when the end date is set:
$('#end').change(function(){
if(this.val() != ""){
var start_date = $('#start').val();
var end_date = $('#end').val();
if(start_date <= end_date){
//After
}else{
//Before
}
}
});
Or at the form submission:
$('#submit').click(function(){
var start_date = $('#start').val();
var end_date = $('#end').val();
if(start_date <= end_date){
//After
}else{
//Before
}
});

Categories