Validate date range in javascript - javascript

Date format is in "mm/dd/yyyy". It is not giving me proper result. It is only validating month.
<input type="text" name="durationstart" id="durationstart" value="">
<input type="text" name="durationend" id="durationend" value="" onclick="return chk_val12()" >
<script>
function chk_val12()
{
var durationstart = document.getElementById('durationstart').value;
var durationend = document.getElementById('durationend').value;
if(durationstart>durationend)
{
alert("Please enter proper duration range");
return false;
}
else
{
return true;
}
}
</script>

You cannot compare validate date like this.
Text box contains the value of string dataType. So what the below code does is
if(durationstart>durationend) // Invalid
Instead parse it to date object.
Updates:
Though it works, there are chances for browser compatibility so here I have written the full date parsing
function chk_val12() {
var durationstart = document.getElementById('durationstart').value;
var durationend = document.getElementById('durationend').value;
var st = durationstart.split("/");
var en = durationend.split("/");
var startDate = new Date(st[2], (+st[0] - 1), st[1]);
var endDate = new Date(en[2], (+en[0] - 1), en[1]);
if (startDate > endDate) {
alert("Please enter proper duration range");
return false;
} else {
return true;
}
}
JSFiddle
FYI: Make sure user enters the right date format.
What it does?
1) Split the dateString you have like
var st = durationstart.split("/");
2) Parse it like new Date(YYYY, MM, DD)
var startDate = new Date(st[2], (+st[0] - 1), st[1]);

Extracting and comparing formatted date strings from text inputs
You'll need to use the Date object's parse method to convert the input strings into milliseconds, then compare the 2:
var durationstart = Date.parse( document.getElementById('durationstart').value );
var durationend = Date.parse( document.getElementById('durationend').value );
This depends upon the input being entered in a way the Date.parse method expects though — in formats following either the Wed, 3 Feb 2014 or 2014-02-03 standards.
Converting arbitrary formats into date objects
If the user is likely to use another input format, you may want to use a plugin such as Sugar to parse a wider range of possible formats. Sugar adds a Date.create( inputString ) method which accepts the following formats.
Using HTML5 #type=date inputs
An alternative for modern browsers is to use inputs of type date instead of text, which would allow you to extract the date values directly without fear of the user entering an unparseable format. Using this method you would change the HTML to:
<input type="date" name="durationstart" id="durationstart" value="">
<input type="date" name="durationend" id="durationend" value="" onclick="return chk_val12()" >
…and use the native valueAsDate method to extract the values as follows:
var durationstart = document.getElementById('durationstart').valueAsDate;
var durationend = document.getElementById('durationend').valueAsDate;

Try this
function dateCheck() {
fDate = Date.parse(document.getElementById("durationstart").value);
lDate = Date.parse(document.getElementById("durationend").value);
if(fDate >lDate )
{
alert("Please enter proper duration range");
return false;
}
else
{
return true;
}
}

Related

Date conversion resulting into time zone issue

I am trying to get functionality - if the user entered date is less than the current date I need to show an error message on the screen, I implemented the following code which is working fine in my local system date but not working in other time zones. Can anyone please help in getting this.
I need to use only javascript or jquery. I was not supposed to use other libraries.
dateFormat = function(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;
}
return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');
}
checkStart = function(value) {
var newDate = new Date().toISOString();
var inputDate = new Date(value).toISOString();
var today = new Date(newDate).setHours(0,0,0,0);
var userDate = new Date(inputDate).setHours(0,0,0,0);
if(userDate < today) {
$('#error-msg3').show();
$('#startDate').val('');
} else {
$('#error-msg3').hide();
}
}
<input type="tel" maxlength="10" id="startDate" name="startDate" placeholder="mm/dd/yyyy"
oninput="this.value = dateFormat(this.value, event)" onblur="checkStart(this.value)" required/>
<span id="error">Start date should not be lesser than the current date.</span>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
Server and Db May run on a different timezone, (UTC preferred ) and when you sen date as a string it doesn't have any timezone there instead it is just a string.
Try sending it as a timestamp or UTC date string
So that server and db will automatically convert it to their timzone and store it. and when any user fetch it from other time zone it will automatically converts to their timezone (but you store string it will just be treated as a string everywhere)
let d = new Date()
console.log(d.getTime())
//or get utc string
console.log(d.toUTCString())
Send this value to your server (API)
Your code runs entirely on the client so timezone is irrelevant.
In the OP there is:
var newDate = new Date().toISOString();
...
var today = new Date(newDate).setHours(0,0,0,0);
The conversion of Date to string to Date to number is inefficient and unnecessary. The following is equivalent:
let today = new Date().setHours(0,0,0,0);
Similarly for inputDate:
var inputDate = new Date(value).toISOString();
...
var userDate = new Date(inputDate).setHours(0,0,0,0);
is equivalent to:
let userDate = new Date(value).setHours(0,0,0,0);
All calculations are local so timezone is irrelevant. Also see Why does Date.parse give incorrect results?
Attempting to control user input using script is always fraught as there are many cases that are either impossible or impractical to code around. The use of a tel input for Dates is an example. The whole issue can be avoided by using a date input and setting a min value to today. Then users can't select a date before today and your issue is solved, e.g.
window.onload = function() {
let dateEl = document.getElementById('dateInput');
dateEl.min = new Date().toLocaleString('en-CA', {year:'numeric', month:'2-digit', day:'2-digit'});
}
<input id="dateInput" type="date">
If you are comparing the date sent by the user to a date on the server, then user system clock accuracy and timezone may be an issue, but that isn't explained in the OP.
If that is an issue, then you need to ask another question on that specific topic.
If you really want to manually control the input date and show an error message when invalid dates are selected, then parse the value from the date input and compare it to the start of today and go from there:
// Parse YYYY-MM-DD as local
function parseYMDLocal(s) {
let [Y, M, D] = s.split(/\D/);
return new Date(Y, M-1, D);
}
// Check if date in YYYY-MM-DD format is before today
function isBeforeToday(d) {
return parseYMDLocal(d) < new Date().setHours(0,0,0,0);
}
function checkValue() {
let errEl = document.getElementById('errEl');
errEl.textContent = '';
console.log(typeof this.value);
if (isBeforeToday(this.value)) {
errEl.textContent = 'Date must be today or later';
} else {
// do something else
}
}
window.onload = function() {
document.getElementById('dateInp').addEventListener('blur', checkValue, false);
}
#errEl {color: red}
<input id="dateInp" type="date"><span id="errEl"></span>

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

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>

Date validation failing

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
}

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