javascript date validation - javascript

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()

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>

(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.

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>

Comparing time and date in javascript

Lets say there are two textboxes, one to enter in a date and the other to enter in time. Below is an example:
<p><strong>Date:</strong> <input type="text" id="datetxt"></p>
Example of how date is displayed: 25-05-1995
<p><strong>Time:</strong> <input type="text" id="timetxt"></p>
Example of how time is displayed: 14:25
Can someone suggest a way in javascript to compare values of the date and time from the textboxes to the current date and time so if the current date and time is past the date and time entered in the textboxes, then it should display and alert?
Try this
var dateParts = document.getElementById("datetxt").value.split("-");
var timeParts = document.getElementById("timetxt").value.split(":");
var valueDate = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0], timeParts[0], timeParts[1]);
if( (new Date).getTime() > valueDate .getTime() )
{
alert("passed");
}
Live example: http://jsfiddle.net/TJEMr/
You need to massage your date string into a compatible date format:
//datetxt textbox value, split on dashes
var date = "25-05-1995".split("-"),
//timetxt textbox value
time = "14:25",
//put it into format: YYYY-MM-DDThh:mm and creates a date object from it
dateObj = new Date(date[2] + '-' + date[1] + '-' + date[0] + 'T' + time);
//if today is greater than we have passed that DateTime
if(new Date() > dateObj) {
alert("After entered date");
} else {
alert("Not passed yet!");
}
Working example: jsFiddle

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