NaN error in Javascript - javascript

When I tab, the result putted in the textbox was NaN. While in my computer at home, it outputs a number. Please help.
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("dob").value;
var date2 = new Date(dob);
var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("ageId").value = age;
document.getElementById("ageId").focus ();
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}

If you pass an invalid date string to Date, you get an invalid Date.
(new Date("9999-99-99"))
If you call getFullYear on an invalid Date, you get NaN.
If you try to perform any arithmetic operations on NaN, you get Nan.
So, your problem is that you tabbed out of you input box and it was empty and this is what was passed to Date in your line:
var date2 = new Date(dob);
You should improve your pattern to eliminate any invalid date.

If you really do search for dd/mm/yyyy date format,
then your pattern should be
/^\d{1,2}\/\d{1,2}\/\d{4}$/
Notice : You're not actually calculating age but the difference between year of birth and current year.
If one's birthday occurs after current date, it will one year wrong.
You could look at this response for a good starting point on building this calculator.

Related

(getDate() - 1) function is getting the value zero if the current date is 1

My Requirement:
I'm having to fields Start Date and End Date, If the End Date is left empty while saving the record, the End Date Field value is populated with plus 1 year based on the entered from date.
My Issue:
If the Start Date is "9/1/2016" and the End Date is Left Empty means it should automatically populate the End Date value as "8/31/2016" but it returning the End Date value as "9/0/2016" and also i'm getting the following ERROR MESSAGE
Error: JS_EXCEPTION
INVALID_FLD_VALUE You have entered an Invalid Field Value Invalid Date for the following field: custrecord_end_date
CODE:
SCRIPT : CLIENT SCRIPT, EVENT :SaveRecord
function saveRecord(scriptContext) {
var newRecord= scriptContext.currentRecord;
var fromDate = new Date(newRecord.getValue('custrecord_created_date'));
var endDate = newRecord.getValue('custrecord_end_date');
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', tempEndDate);
}
}
// Add Plus Year from the Start Date when the End Date is Empty
function addingPlusYearOfTheCurrentDate(fromDate ) {
var date = new Date();
var Month = (fromDate.getMonth() + 1);
var Dates = (fromDate.getDate() - 1);
var Year = (fromDate.getFullYear() + 1);
var last_Day = new Date(Month + '/' + Dates + '/' + Year);
log.debug('last_Day:', last_Day);
return last_Day;
}
Not sure why you expected to be able to subtract 1 from 1 and get anything other than 0, but you can solve this problem by using the Date object's setFullYear() and setDate().
function addingPlusYearOfTheCurrentDate(fromDate) {
var date = new Date(fromDate);
date.setFullYear(date.getFullYear() + 1);
date.setDate(date.getDate() - 1);
return date;
}
console.log(addingPlusYearOfTheCurrentDate(new Date(2015, 10, 1)));
You should use the method nlapiStringToDate() for string to date conversions, as NetSuite gives date field value as string, which you must convert to date, and before you set back date, you must use nlapiSetFieldValue(YOUR_FIELD_ID, nlapiStringToDate(dateObject))
Please see below on suggested usage on reading and setting date fields.
function saveRecord(scriptContext) {
var newRecord = scriptContext.currentRecord;
var fromDate = nlapiStringToDate(newRecord.getValue('custrecord_created_date'));
var endDate = nlapiStringToDate(newRecord.getValue('custrecord_end_date'));
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', nlapDateToString(tempEndDate));
}
Parsing strings with the Date constructor (and Date.parse, they are equivalent for parsing) is strongly recommended against since parsing is almost entirely implementation dependent and inconsistent. Manually parse strings with a custom function or use a library.
Adding a year to a Date is fairly simple, but it seems you want the date that is one day prior to the same date next year. So add one year then subtract one day.
// Parse m/d/y format string to a Date and validate the result
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
// Add 1 year to a Date
function addYear(d) {
if (Object.prototype.toString.call(d) != '[object Date]') return;
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate() -1);
return d;
}
var d = parseMDY('9/1/2016');
console.log(d.toLocaleString())
addYear(d);
console.log(d.toLocaleString())
Note that for 29 February, adding one year gives 1 May, then subtracting one day will give 28 February.
Is this a 1.0 or 2.0 script?
NetSuite's 1.0 API offers a couple date manipulation methods that might be helpful to you here: nlapiAddMonths and nlapiAddDays, as well as the Date-String conversion methods.
Here's an example of what you could do in 1.0
// 1.0 API does not pass scriptContext to saveRecord
function saveRecord() {
// Use nlapiStringToDate instead of raw Date constructor
var fromDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_created_date'));
// Instead of the full extra conditional, just use || as fallback
var endDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_end_date')) ||
calculateEndDate(fromDate);
// setting the value to the End Date Field
nlapiSetFieldValue('custrecord_end_date', nlapiDateToString(endDate));
}
/** #param fromDate {Date} */
function addYear(fromDate) {
return nlapiAddMonths(fromDate, 12);
}
/** #param fromDate {Date} */
function dayBefore(fromDate) {
return nlapiAddDays(fromDate, -1);
}
/** #param startDate {Date} */
function calculateEndDate(startDate) {
// add 1 year first, then subtract one day
return dayBefore(addYear(startDate));
}
If you're using 2.0 just add a comment, and I will try to update the example if I can. If you've got any questions about how this works, feel free to let me know as well.

Automatic display age after filling out birth date with a format of YYYY-MM-DD

Actually I already posts it here. It's solved by someone here but after I tried it again now, it fails again. Please help.
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("dob").value;
var date2 = new Date(dob);
var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
//Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("ageId").value = age;
document.getElementById("ageId").focus ();
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}
Your function is perfect just need to change the regular expression:-
So instead of
var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
//Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
Only write
if (dob.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/)) {
and the date format will be
dd-mm-yyyy
I tried to use your code, and to me it looks like it's working. I put it in a jsFiddle and it seams ok to me.
Although the age calculation is rather rough, something like the following code would calculate exacter ages, since someone whose birthday is still this year will have an age shown that he will have on his next birthday.
Something like this would calculate the age:
function calculateAge(date1 , date2) {
var ageDifs = date1 - date2.getTime();
var ageDate = new Date(ageDifs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Your error message Invalid date format. Please Input in (dd/mm/yyyy) format! does not match your input format yyyy-mm-dd. Which one do you want to use?
I created an extended jsFiddle for that
In case you need dd/MM/yyyy I created an new jsFiddle, doing a better date validation and more accurate age calculation
dd/mm/yyyy jsFiddle

How to automatic populate age field after filling up birthdate with a format of YYYY-MM-DD using JS

Please help. I tried this code but I wasn't able to change it's format. I need the date to accept the format YYYY/MM/DD
<script type="text/javascript">
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("dob").value;
var date2 = new Date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
//Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("ageId").value = age;
doucment.getElementById("ageId").focus();
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}
</script>
You just need to change the regex from
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
to
var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
And it should do.
Check Here : http://jsfiddle.net/fP875/
WARNING
But remember the regex you are using is not exactly correct. You'll need a more precise regex to check date.
Your regex will accept dates like 2014-23-56 or 9999-99-99.
I'll recommend this : https://stackoverflow.com/a/18759740/3603806
if you need accurate dates and not just formatting.
http://jsfiddle.net/EywSP/856/
http://jsfiddle.net/EywSP/854/
just take this
javascript date manipulation library [closed]
I wrote a javascript date library called moment.js
https://github.com/moment/moment
It creates date wrapper objects so that it doesn't have to modify
Date.prototype.
It includes parsing from strings, date objects, and unix timestamps.
It can format based on replacement patterns ("dddd, MMMM Do YYYY,
h:mm:ss a") and also includes time ago ("2 days ago", 6 months ago")

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
}

ReferenceError: date is not defined

I have some code here where I get a value from a form represented by "adate". Then I split the string the user enters at the hyphen and separate each value into year, month and day as you can see. I use those values to define a date object. My console correctly displays the date, but I keep getting this error also showing up. Am I defining the date incorrectly? I'm not sure what the issue is.
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task")) return;
var adate = document.getElementById("dueDate").value;
var reString = new RegExp("[0-9]{4}\\-\[0-9]{2}\\-\[0-9]{2}");
if ( adate.match(reString)) {
processDate(adate) }
else {
alert("you did not enter the date in the correct format")
};
var id = (new Date()).getTime();
var todoItem = new Todo(id, task, who, date);
todos.push(todoItem);
addTodoToPage(todoItem);
saveTodoItem(todoItem);
hideSearchResults();
}
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
console.log(date);
}
Make your function return the date, because the date variable in there is not visible to the outside:
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
return new Date(year, month, day);
}
Then assign to a new variable when you call it:
var date = processDate(adate);
The error actually originated in the following line, because you were referencing a non-existing date variable:
var todoItem = new Todo(id, task, who, date);
Just a comment.
The RegExp constructor is usually only required where the expression is dynamically generated. Where you have a fixed expression, it's simpler to use a literal (as you don't have to quote certain characters). Also, to test the format, a more appropriate method is test rather than match.
If the date format is: yyyy-mm-dd, consider:
var reString = /^\d{4}-\d\d-\d\d$/; // trim leading and trailing white space?
if (reString.test(adate)) {
processDate(adate);
}
The date string validation should be in the processDate function, which might throw different errors depending on whether the format is incorrect or the date is invalid (e.g. 2013-02-29, which will return a date of 2013-03-01 in your current code).

Categories

Resources