Date validation failing - javascript

I wish to check whether a one given date is less than the other date using JavaScript + jQuery.
However, when checking a date that is one day less than the given date, the condition is not met.
This is my code;
$('#payment_date').change(function(){
payment_date_1 = String($("#payment_date").val());
s_date_1 = String($("#s_date").text());
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date<s_date){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
ex: when s_date == '2013-07-02' and payment_date == '2013-07-01' the condition is returning false rather than true.
My HTML:
<span style="display:none;" id="s_date">2013-07-02</span>
<input type="text" value="" name="payment_data_info[payment_date]" id="payment_date" class="hasDatepicker" readonly="readonly">
Note; I have checked if both dates are valid, two dates are returning valid dates and the condition is working perfectly well for other instances
I just found out why; I'm using jQuery's date picker. Dates less than and equal to 2013-07-10 returns a valid date and dates less than 2013-07-10 and larger than 2013-06-30 returns an invalid date. Any idea why?

First of all check if variable declaration is the problem, than check if the string parsing returns the dates you're expecting. Maybe s_date and payment_date are invalid after all?
I expierenced difficulties too with the direct comparison (don't know why), so I used the valueOf-function to get values for comparison.

Sure it works ;)
http://jsfiddle.net/4MQkK/
payment_date_1 = "2013-07-01";
s_date_1 = "2013-07-02";
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date < s_date){
alert(payment_date + "is lower than " + s_date);
}
Check your values of payment_date_1 and s_date_1 at least one of them could not be parsed correctly

Try this , I hope it will help.
$('#payment_date').change(function(){
var payment_date_1 = $("#payment_date").val(); //add var
var s_date_1 = $("#s_date").text(); //add var
var payment_date = new Date(payment_date_1);
var s_date = new Date(s_date_1);
if((payment_date.valueOf())<(s_date.valueOf())){
alert("please enter a correct date");
$("#payment_date").val("");
}
});

2 Possible Causes:
1) Where Date is called as a constructor with more than one argument,
if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new Date(2014,1,1),
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
your date format is 'dd/MM/yyyy' but new Date () use format yyyy/dd/mm so 2013-06-30: 30 is month i.e. 30 month more then 06/01/2013 --> 06/06/2015
you need to change the format. for example:
var myDate = "2013/01/30"
var split= myDate .split("/");
new Date (split[2],split[1],split[0]);
2) months in Date() in javascript they numeric 0-11. so 01/03/2013 changed to 01/04/2013
int month = myMonth -1; // for example: mymonth = 'March' => month = 2
can use new Date(2013,month,30);

You can do something like this.
var payment_date_1 = $("#payment_date").val();
var s_date_1 = $("#s_date").text(); or $("#s_date").val();
// IF s_date_1 is a input field then you have to use .val()
For typecast String. You can do
var payment_date_1 = $("#payment_date").val().toString();
var s_date_1 = $("#s_date").val().toString();

PLease create date objects and then check
var first = new Date($("#s_date").text());
var second = new Date($("#s_date_1").text());
if(first.getTime() < second.getTime()) {
// code
}

Related

get date and month from html5 datefield javascript

I have a date field which looks like this
var date_input = document.getElementById('date_cust');
date_input.onchange = function(){
alert("The date you selected is : "+date_input.value);
}
<input autocomplete="off" type="date" class="form-control" id="date_cust" name="date_cust" required />
and resulted/alerted something like this:
``The date you selected is: 2020-01-20``
I want to know is there any ways to get only the date and the month, because I want to compare the date and the month with the date and the month which I already set, for example, 31st of March (31-03 / 03-31). Something like this.
var 31march = '03-31';
if (extracted_data == 31march) {
alert("Happy Birthday");
} else {
alert("Not your birthday yet.")
}
I already tried to parse the value like this:
var date_input = Date.parse(document.getElementById('date_cust').innerHTML);
but it resulted in NaN
is there any other ways for this case?
Thank you in advance.
Use getMonth() from new Date():
const myDate = new Date('2020-01-30')
console.log(myDate.getMonth())
//0 = january
//1 = February
...
DOCS
You can split the date and get the parts that you need
var dateArr = date_input.value.split("-");
console.log('year: ' + dateArr[0])
console.log'month: ' + (dateArr[1])
console.log('day: ' + dateArr[2])
var new_date = dateArr[2] + '-' + dateArr[1];
console.log(new_date)
To get the date from the input element, you must use the new Date() method passing the value attribute of the input as param.
var dateCustom = new Date(this.value);
this refers to the input element because you will use in the event handler.
Then, use the getDate() and getMonth() JS methods to extract the day of the month and the month.
var date_input = document.getElementById('date_cust');
date_input.onchange = function(){
var dateCustom = new Date(this.value);
document.getElementById('day').textContent = dateCustom.getDate();
document.getElementById('month').textContent = dateCustom.getMonth() + 1;
}
<input autocomplete="off" type="date" class="form-control" id="date_cust" name="date_cust" required />
<p id="day"></p>
<p id="month"></p>
Since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.
E.g. in moment.js you might write:
let m = moment(date_input.value).format('MM-DD');
Where:
MM stands for month number (eg: 01-12)
DD stands for day of the month (eg: 01-31)
Read the moment docs here: https://momentjs.com/docs/
More information about why it is giving you a NaN as result can be found here: Why does Date.parse give incorrect results?
use this:
getDate()
const yourDate = new Date('2019-03-10');
console.log(yourDate.getDate())
console.log(yourDate)
**variable in js can't be start with a number "var 31march = '03-31';"
should be for example var march31 = '03-31' ;
**
these are the set of rules you should consider:
1-Names can contain letters, digits, underscores, and dollar signs.
2-Names must begin with a letter
3-Names can also begin with $ and _ (but we will not use it in this tutorial)
4-Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
Here is the code that might work for you:
var date_input = document.getElementById('date_cust');
date_input.onchange = function() {
var birthday = '3-31';
let dateSelected = new Date(date_input.value);
let dateMonth = (dateSelected.getMonth() + 1) + '-' + dateSelected.getDate() ;
if (dateMonth === birthday) {
alert("Happy Birthday");
} else {
alert("Not your birthday yet.")
}
}
but it is better to split the date input value by - so that you know first value is the year, and the second one is a month and third one is a year.
Here is my code pen link: https://codepen.io/gideonbabu/pen/ZEYdzLj

How to compare dates to make sure Google Apps Script is only sending an alert once a day?

I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this?
I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately.
function sendAlert{
var now = new Date();
var yearNow = now.getYear();
var monthNow = now.getMonth() + 1;
var dayNow = now.getDate();
var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT');
var sentYear = sheet.getRange("R2").getValue();
var sentMonth = sheet.getRange("S2").getValue();
var sentDay = sheet.getRange("T2").getValue();
if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) {
sendEmail();
var sentYear = sheet.getRange("R2").setValue(yearNow);
var sentMonth = sheet.getRange("S2").setValue(monthNow);
var sentDay = sheet.getRange("T2").setValue(dayNow);
else {
Logger.log('Alert was already sent today.');
}
}
I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again.
Requirement:
Compare dates and send an email if one hasn't been sent already today.
Modified Code:
function sendAlert() {
var sheet = SpreadsheetApp.getActive().getSheetByName('blank');
var cell = sheet.getRange(2,18); //cell R2
var date = new Date();
var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd");
var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd");
if (alertDate !== currentDate) {
sendEmail();
cell.setValue(date);
} else {
Logger.log('Alert was already sent today.');
}
}
As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate.
References:
Utilities.formatDate()
Class SimpleDateFormat

Trying to remove all the passed dates

I have an array with many dates, they are not in the date type but string like: "2016-08-12" for example. Then what I would like to do is to remove all dates that we already have passed. So therefor im trying to compare them to todays date and then remove it if its passed. Using typescript by the way.
my array, named datoArray, looks like this:
["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]
just with a lot more of the same...
then here's what I try to do:
for(var i = 0; i < this.datoArray.length; i++){
this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
this.skoleDag = parseInt(this.datoArray[i].slice(8,10))
if(this.skoleAar < dagensAar){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned < dagensMaaned){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned == dagensMaaned && this.skoleDag < dagensDag){
this.datoArray.splice(i, 1);
}
}
the "dagensAar", "dagensMaaned" and "dagensDag" variables im getting from another function that works. If i "console.log" the variables it prints out int values like 2016 for the year and 8 for the month if i take from the start of the array, and for the "dagensAar", "dagensMaaned" and "dagensDag" it prints 2016 11 20, which is todays year, month and day. all is in Int type, so what im not getting here is why my "if" doesnt work? It seems like there is something wrong with the way i compare the, but i thought this was the way to compare int values?
If the dates are in ISO-8601 format then you can simply filter using Date.parse().
var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];
function removePastDates(data) {
var today = new Date();
console.log('Initial state: ' + data);
var modified = dates.filter(function(dateString) {
return Date.parse(dateString) >= today;
});
console.log('Final state: ' + modified);
return modified;
}
var newDates = removePastDates(dates);
Your dates seem to be RFC compliant, meaning they can be directly fed into a new Date object. Simply compare to today and filter by that:
var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)
(pre-ECMA6:)
var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
return new Date(d) >= today;
})
I think the problem is not related to the dates.
I think the problem is that you are removing items from the array while looping the same exact array.
You should maybe try looping from the end of the array to the beginning or just save the indexes that you need to remove and later do the actual removing.
Keep in mind that when you remove an item you change the index of every item in the remaining of the array - maybe you should start removing from the greatest index so it will not confuse you.

Date input type validation in javascript?

I can't quite figure out how to validate a date input type in javascript. I tried looking on the internet but I just couldnt find anything.
I have one field that ask the user to input its birthday. I want to validate it in javascript with the certain limits on days months and, especially years. For example if the user input more than 2016(or the current year) it would give an error.
I can't quite figure out how to "extract" the date input type and control every elements of it (day, month, year).
Here part of my html
<form method="POST" action="request.jsp" onsubmit="return validate()">
Date of birth: <input type="date" id="bday" name="bday" value="">
</form>
Javascript:
var birthday = document.getElementById('bday').value;
This is all i've got.. please help?
TLDR
You have to parse the string as a date (JavaScript provides the Date API for this very use case).
Full answer
You're on the right track. Here's a JSBin example I did. Try opening the console and changing the date, and you'll see it logged.
$('#birthday').on('change', function() {
console.log(new Date(this.value));
});
(I'm using jQuery in the above example just for convenience sake, but you can use whatever you want.)
The problem you have here is that the date is logged as a string. You can use the JavaScript Date object to parse the string.
Based on whatever validation you want to do, you can use various date object methods (like getFullYear, for example) and match those against the input.
I'll leave the full implementation up to you, but the inside of the change handler might look like:
var date = new Date(this.value);
if(date.getFullYear() > 2016) {
// do something (like show a message, for example)
}
If you are able to get the value of the input element with:
var birthday = document.getElementById('bday').value;
Then birthday will be available to you as a string (all input values are always returned to JavaScript as strings). From there, you'd need to convert that string to a date with:
var dob = Date.parse(birthday);
Then, once you've got the entire date, you can extract the pieces of it with the various JavaScript Date/Time methods:
var month = dob.getMonth(); // months start counting from zero!
var day = dob.getDate();
var year = dob.getFullYear(); // getYear() provides 3 digit year!
Here's a working example:
var birthday = null, btn = null, output = null;
// Wait until the document is ready for interaction:
window.addEventListener("DOMContentLoaded", function(){
// Get references to DOM elements needed:
birthday = document.getElementById('bDate');
btn = document.getElementById('btnGetDate');
output = document.getElementById('result');
// Set up an event callback for when the button gets clicked:
btn.addEventListener("click", function(){
// Create a new Date that converts the input date
var dob =new Date(birthday.value);
alert(dob);
// Extract pieces of the date:
var month = dob.getMonth(); // months start counting from zero!
var day = dob.getDate();
var year = dob.getFullYear();
// Now that you have the pieces of the date, you can validate as you wish:
// e.g. if(year > 2016) { . . . }
// Write out date:
output.innerHTML = ++month + "/" + ++day + "/" + year;
});
});
<input type="date" id="bDate">
<input type="button" id="btnGetDate" value="Get Date">
<p id="result"></p>
NOTE: Keep in mind that Daylight Savings Time will have an effect on
the result depending on what time of day it is. See:
How to check if the DST (Daylight Saving Time) is in effect and if it is what's the offset?
for more info. on that.
Input type date is not supported in all browsers, so you should detect that and replace the input with a suitable alternative that includes the format that is required.
Where supported, the input will return an ISO 8601 format date string without a time zone. According to ISO 8601, this should be treated as local, but TC39 in their wisdom decided that it should be treated as UTC, so that is what Date.parse (and the Date constructor) will do in most cases. In some it will be treated as local and in IE 8 as invalid. So for systems with a timezone that is west of Greenwich, Date.parse('2016-03-20') will return a Date object that, when displayed as a local date, will be '2016-03-19', i.e. one day early.
So you should manually parse the date string, validate the date using one of the many answers here, then check whether the year, month and day are within your constraints.
if you're simply trying to validate whether or not a string is a valid date, you can just check that it creates a valid date object.
function isValidDate(d){
return !isNaN((new Date(d)).getTime());
}
https://jsfiddle.net/46cztok6/
so your validate() function would look like this.
function validate(){
var birthday = document.getElementById('bday').value;
if(!isValidDate(birthday)){
alert("you did not enter a valid birthday");
return false;
}
}
Here is a bin so you can have an idea how to start validating this type of field: https://jsbin.com/lifacaxonu/edit?html,js,console,output
$('#birthday').on('change', function() {
var val = this.value.split('-');
if (val[0] > new Date().getFullYear()) {
console.log('invalid')
} else {
console.log('ok')
}
});
After looking out for 3 hours, i wrote this and achieved dd/mm/yyyy date input using plain Javascript.
<div class="container">
<div class="datetime-container">
<input type="text" placeholder="write your date" id="datetime" onblur="validateDate()">
<p id="error"></p><br>
<input type="tel" maxlength="10" placeholder="dd/mm/yyyy"
oninput="this.value = DDMMYYYY(this.value, event)" />
</div>
</div>
<script>
function DDMMYYYY(value, event) {
let newValue = value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');
const dayOrMonth = (index) => index % 2 === 1 && index < 4;
// on delete key.
if (!event.data) {
return value;
}
let currentYear = new Date().getFullYear();
console.log(newValue.slice(2,4));
if(newValue.length>=2 && newValue.slice(0,2)>31){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(0,2),31);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid day!";
}else if(newValue.length>=4 &&newValue.slice(2,4)>12){
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid month!";
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(2,4),12);
}else if(newValue.length==8 && newValue.slice(4)>currentYear){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(4),currentYear);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid year!";
}
else{
document.getElementById("error").style.display="none";
}
return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');;
}
</script>

JavaScript - Validate Date

I have an HTML text field. I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?
I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?
You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.
function checkDate(m,d,y)
{
try {
// create the date object with the values sent in (month is zero based)
var dt = new Date(y,m-1,d,0,0,0,0);
// get the month, day, and year from the object we just created
var mon = dt.getMonth() + 1;
var day = dt.getDate();
var yr = dt.getYear() + 1900;
// if they match then the date is valid
if ( mon == m && yr == y && day == d )
return true;
else
return false;
}
catch(e) {
return false;
}
}
Is it true that JavaScript can't validate dates?
No.
Is there a function that does this?
No.
You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.
Check out http://momentjs.com/. Using it, this snippet
moment(yourCandidateString, 'MM-DD-YYYY').isValid()
should do the job.
This is what I use to validate a date.
Date.parse returns NaN for invalid dates.
This supports both date-only and date+time formats.
Hope this helps.
var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);
If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.
I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.
http://www.eyecon.ro/bootstrap-datepicker/
<input type="text" id="dateinput"/>
<script type="text/javascript">
$(#"dateinput").datepicker({
buttonImage: "images/calendar.png",
dateFormat: "yyyy-MMM-dd"
});
function validateDate() {
if ($(#"dateinput").val().trim() == "") {
// Is a blank date allowed?
return true;
}
var oldVal = $(#"dateinput").val(); // Current value in textbox
// Now use jQueryUI datepicker to try and set the date with the current textbox value
$(#"dateinput").datepicker("setDate",$(#"dateinput").val());
// Check if the textbox value has changed
if (oldVal != $(#"dateinput").val()) {
// The datepicker will set something different if the date is invalid
$(#"dateinput").val(oldVal); // Set the textbox back to the invalid date
alert ("date was invalid");
return false;
} else {
// If nothing changed, the date must be good.
return true;
}
}
</script>
There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:
<script type="text/javascript">
/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
</script>
Source: http://www.javascriptkit.com/script/script2/validatedate.shtml
Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.
I suggest you a couple of solutions.
guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.
use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.
Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.
> datestring_valid = "2020-02-29";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false
NB: This requires the date string to be ISO formatted.
The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.
A function that handles all of this is the following:
function isValidDateString(datestring) {
parsed_Date = new Date(datestring);
return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false

Categories

Resources