Is there any function to get the input that was provided to moment()
In the example below, inputDate becomes null.
var date = moment("invalid date");
if(!data.isValid()){
return { message: "Invalid date", inputDate: date }
}
I can access the input using internals i.e. date._i but was wondering if there's any function that would return the input provided to moment constructor.
You can use creationData()
After a moment object is created, all of the inputs can be accessed with creationData() method:
moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
input: "2013-01-02",
format: "YYYY-MM-DD",
locale: Locale obj,
isUTC: false,
strict: true
}
Here a live example:
var date = moment("invalid date", moment.ISO_8601);
console.log(date.creationData().input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
As a side note:
I've used moment.ISO_8601 in my snippet to prevent Deprecation Warning, as shown here.
Something quite similar was asked (but not a duplicate) was asked here.
I am validating the dates using moment.js
var dobfield = $("#dobfield").val().trim();
//...
formatToApply = "DD/MM/YYYY";
//...
else if(moment(dobfield, formatToApply).isAfter(moment().format(formatToApply)))
{
swal({
title: "",
text: "Date of birth has to be in the past! "
});
$("#dobfield").focus();
}
else if(moment(dobfield, formatToApply).isSame(moment().format(formatToApply)))
{
swal({
title: "",
text: "Date of birth cannot be in the present! "
});
$("#dobfield").focus();
}
Both the isSame and isAfter fails to validate the date given in dd/mm/yyyy format.
I assume you just want to compare just the date, not the time. So you have to indicate that to the isSame() and isAfter() functions...
var dobfield = $("#dobfield").val().trim();
...
formatToApply = "DD/MM/YYYY";
...
else if (moment(dobfield,formatToApply).isAfter(moment(),'day')) {
swal({
title: "",
text: "Date of birth has to be in the past! "
});
$("#dobfield").focus();
}
else if (moment(dobfield,formatToApply).isSame(moment(),'day')) {
swal({
title: "",
text: "Date of birth cannot be in the present! "
});
$("#dobfield").focus();
}
Here you have a fiddle example... https://fiddle.jshell.net/rigobauer/mz9rutuq/
NOTE: dobfield date format always has to match with the format specified in formatToApply variable. Otherwise, moment(dobfield,formatToApply) will get unexpected result.
In my case the issue is outdated version of moment.js
Sadly , moment.js isAfter and isSame is not wokring for this date format . it is only working for YYYY-MM-DD .
This is a bug from moment.js i could say .
I'm creating a new online store and the client has asked for the following, basically a piece of text that says:
Standard delivery:
Order now and receive before xxx date (this should be 3 days ahead of the date)
Next day delivery:
Order now and receive before xxx date (this should be the following day)
Can anyone point me in the right direction of a script to achieve such?
Many thanks!
$normal=date("d.m.Y",strtotime("+3 days"));
$express=date("d.m.Y",strtotime("+1 day"));
Please remember to set the default timezone.
Live Demo
function pad(str) {
return ("00"+str).slice(-2);
}
function formatDate(d) {
return ""+pad(d.getMonth()+1)+"/"+
pad(d.getDate())+" "+
d.getFullYear();
}
$(function() {
var now = new Date(<?php echo time(); ?>*1000);
now.setDate(now.getDate()+1);
$("#nextday").text(formatDate(now));
now.setDate(now.getDate()+2);
$("#threedays").text(formatDate(now));
});
Assume in my text box user enter like
18-06-2010 ,
Validation RULE if date is greater then current date then program should through the validation error like ,
PELASE ENTER PAST OR CURRENT DATE, DONT CHOOSE FUTURE DATE ,
Thanks
The date format you've specified is not recognized by javascript. Here's a script that makes some minor validity checking, but still some rough assumptions that the value entered conforms to the format above, and tries to construct the date string '2010/06/08' out of that.
var txtDate = document.getElementById('myTextBox').value;
var dateParts = txtDate.split('-');
if(dateParts.length != 3) {
alert('invalid date!');
return false;
}
var testDate = new Date(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);
if(isNaN(testDate.getDate())) {
alert('invalid date!');
return false;
}
Implement further error checking as you see fit. Once you know testDate is a date, you can compare it the current date: testDate > new 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