Function to get the input provided to momentjs - javascript

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.

Related

momentjs for only time value

I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601);
let date = '',
time = '';
if (dateAndTime) {
if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) {
date = moment(dateAndTime).format('YYYY-MM-DD');
}
if (moment(dateAndTime, 'HH:mm', true).isValid()) {
time = moment(dateAndTime).format('HH:mm');
}
}
this code works just fine if component.props.data.value contains date and time like 2018-05-22 14:45 or if it contains only date like 2018-05-22. The problem is sometimes component.props.data.value contains only time like 14:45, so moment(component.props.data.value, moment.ISO_8601) doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?
You can use moment(String, String[]), as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);

Moment.js Invalid date message

Im exploring moment.js with Datatables, and its really good for showing the date in the format that I want but there is a problem that i have with the data that I am converting.
If the date is not valid it shows the message INVALID DATE, wihch is good but not what I really want.
Is it possible to, insted of showing "Invalid Date" message, show what was in there originally?
Like if it is not a date I want to see what it is, not that message.
Thanks!
EDIT:
Thanks for your help guys!
I have done this for the datatable "aoColumns":
{ "mData": "APE",
"render": function(mData){
if(mData != null){
if(moment(mData).format("DD/MM/YYYY")== 'Invalid date')
{
return mData;
}
else
{
return moment(mData).format("DD/MM/YYYY");
}
}
},
sDefaultContent: ''},
moment.updateLocale(moment.locale(), { invalidDate: "ur msg or NaN/null" });
var dateStr = "aw 2017-06- awd 09 10:05:21.0";
//var dateStr = "a2017-06-09 10:05:21.0";
if(moment(dateStr, moment.ISO_8601).isValid()){
alert("Valid Date: " + moment(dateStr).format('MM/DD/YYYY'));
}
else {
alert("Invalid Date: " +dateStr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Try creating your own function where you check if the date is valid or not,
see moment validation and if it is not valid return the original data for the message.
Update: Please see this post for extra explanation on the code snippet
Depending on how you've implemented Moment.js, you could simply check the return value from moment? For example
var prettyDate = moment()...;
if(prettyDate != 'Invalid date') {
// set your date
}

ExtJs datefield converts invalid date to valid date

I am using ExtJS 2.1 and I have the following problem, I hate a 'datefield'. Now the date has to be entered in the format 'MM/DD/YYYY'. The problem is if the user enters something like '21/17' or '16/05' it gets converted to a valid date. (21/17 gets converted to 9/17/2015 and 16/05 gets converted to 4/05/2015). How do I override this behavior? I tried writing my own validator but that didn't help either, even if my validator returns 'false' the conversion still happens. Here is the code below:
var d = new Ext.form.DateField({
el: el.dom,
id: id,
format: 'm/d/Y',
hideTrigger: false,
allowBlank: true,
disabled: isDisabled,
validator: testForShortDate,
validateOnBlur: true,
minLength:6,
//validationEvent: false, //string or boolean
invalidText: 'Enter date as MM/DD/YYYY',
menuListeners: Ext.applyIf({
select: function (m, d) {
Ext.form.DateField.prototype.menuListeners.select.apply(this, arguments);
this.focus.defer(100, this);
onDateSelect(m, d, this);
}
})
});
d.render();
d
function testForShortDate(date) {
if (date.split("/").length != 3) {
console.log(date.split("/").length);
return false;
}
return true;
Can anyone help?
There are alternative date formats which ExtJS will try to use if the datefield's value cannot be parsed using the configured format. These formats can be defined using the altFormats property.
By default the value is:
m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d
which explains why something like 21/17 gets converted to 9/17/2015, as the format m/d is used here (the "21st" month of 2014 is really the 9th of 2015).
If you want to disable this altogether, just set the property to an empty string:
altFormats: ''

How does beforeShowDay method work? (Jquery UI datepicker)

I have been trying to find a clear explanation for a significant amount of time now but I just can't seem to understand how this method works. Below is the official documentation from the Jquery UI API. It may be clear to others but I find it a bit vague. I simply want to take an array of dates and disable them. I am able to make all dates not selectable but not the ones I want.
beforeShowDayType: Function( Date date )
Default: null
A function that takes a date as a parameter and must return an array with:
[0]: true/false indicating whether or not this date is selectable
[1]: a CSS class name to add to the date's cell or "" for the default presentation
[2]: an optional popup tooltip for this date
The function is called for each day in the datepicker before it is displayed.
This is my (incomplete) code so far.
$(document).ready(function() {
var array = ["2014-01-03","2014-01-13","2014-01-23"];
$('#fromDate').datepicker({
dateFormat: "yy-mm-dd",
beforeShowDay: function(date) {
{
return [false, "", "Booked out"];
} else {
return [true, "", "available"];
}
}
});
});
Try this:
beforeShowDay: function(date) {
if($.inArray($.datepicker.formatDate('yy-mm-dd', date ), array) > -1)
{
return [false,"","Booked out"];
}
else
{
return [true,'',"available"];
}
}

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