JSP Date validation - javascript

I have an jsp page where the user selects two dates. I need to validate this date to ensure that the 1st date is not less than today's date. This is the script I am using:
var todaysDate = new Date();
if(document.frm.rentedOnDate.value < todaysDate )
{
alert("Rented date should not be before today");
document.frm.bank.focus();
return false;
}
if(document.frm.rentedOnDate.value> document.frm.returnDate.value )
{
alert("Return date should be after rented date");
document.frm.bank.focus();
return false;
}
These are the date selection fields:
<p>Select Rental Date: <input type="date" name="rentedOnDate"> </p>
<p>Select Return Date: <input type="date" name="returnDate"> </p>
The second script function works when the user enters a return date which is before the rented date but the first function does not work. Any ideas why?

Your second test is comparing strings, so I wouldn't count on it being perfectly reliable (a preceding zero could break it for instance).
You need to convert the strings (the .value fields) to proper date objects, and then compare them. This will resolve your first check, and improve your second check.
This function will parse a date provided in the "yyyy-mm-dd" fashion (optional 2-digit year yields 20xx). null is returned for an invalid date.
function getDate(str)
{
var dateParts = /^(\d\d(?:\d\d)?)-(\d\d?)-(\d\d?)$/.exec(str);
if (dateParts === null)
{
return null;
}
var year = parseInt(dateParts[1]);
if (year < 100)
{
year += 2000;
}
var month = parseInt(dateParts[2]) - 1;
var day = parseInt(dateParts[3]);
var result = new Date(year, month, day);
return year === result.getFullYear()
&& month === result.getMonth()
&& day === result.getDate() ? result : null;
}

function validateDate(dates){
re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
if(regs = dates.match(re)) {
// day value between 1 and 31
if(regs[1] < 1 || regs[1] > 31) {
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
return false;
}
var maxday=days[regs[2]-1];
if(regs[2]==2){
if(regs[3]%4==0){
maxday=maxday+1;
}
}
if(regs[1]>maxday){
return false;
}
return true;
} else {
return false;
}
}

Related

inncorrect date validation when year like 'dd.mm.0302' or '27.08.0974' in JS

I have a problem with date validation from database, some years in the date fields are incorrect (like 28.02.0302), i must validate them. I try some functions from web but they validate this date as valid. How to get them work?
Here function that i tried:
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
function isValidDate11(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Because the date you are trying: 28.02.0302 with your script actually change that date to the 28 of February of the year 2202. So it's actually a valid date.
There are two part of that script that result in your date actually being checked as 2202:
This part remove leading Zeroes from the date values making the year from 0302 to 302.
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
This second part check if the date is less than 4 characters and add 2000 if is less than 50 and 1900 if is more.
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
The second part is a bit more tricky. I guess that it was made to validate a date of 01.01.12 as 01/01/2012 and a date of 01.01.93 as 01/01/1999
Those are not really necessary and you can change the function to:
function isValidDate11(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Still the date 28.02.0302 is valid because it get checked as the 28 of February of the year 302.
So to get an exact answer you should probably say exactly what you consider a valid date and what you don't.
Since you have trouble with 0302 I guess you might want a date with a 4 numbers year that doesn't have a leading zero:
function isValidDate11(s) {
// format D(D)/M(M)/YYYY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{4}$/;
if (dateFormat.test(s)) {
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
if(dateArray[2].length != 4){
return false;
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
This will fix your 0302 year problem but will not work with a date ending with a year with only two carachters .14

How do I validate yyyy-mm-dd hh:mm:ss format

I saw this fiddle for validating mm/dd/yyyy or mm-dd-yyyy but I would like to validate yyyy-mm-dd hh:mm:ss format also how do I ensure that today is lesser than from date with the yyyy-mm-dd hh:mm:ss format?.
this is how I have initiated my date time picker..
$("#startDate, #endDate").datetimepicker({ dateFormat: 'yyyy-mm-dd hh:mm:ss'});
Please do help me to get this done.
Thanks
The date format that you have specified is ISO 8601. Most modern browsers support Date parsing of this string format. So you can do something like this.
Javascript
var iso8601 = "2013-02-01 10:00:00",
userDate = new Date(iso8601),
today = new Date(),
dateTime,
date,
time,
value;
// check is valid date
if (isNaN(userDate)) {
alert("invalid userDate");
}
// check if userDate is before today
if (userDate.getDate() < today.getDate()) {
alert("userDate is in past");
}
// check the string specifically matches "yyyy-mm-dd hh:mm:ss" and is valid
function isGregorianLeapYear(year) {
return year % 400 === 0 || year % 100 !== 0 && year % 4 === 0;
}
function daysInGregorianMonth(year, month) {
var days;
if (month == 2) {
days = 28;
if (isGregorianLeapYear(year)) {
days += 1;
}
} else {
days = 31 - ((month - 1) % 7 % 2);
}
return days;
}
if (typeof iso8601 !== "string") {
alert("not an iso8601 string");
} else {
dateTime = iso8601.split(" ");
if (dateTime.length !== 2) {
alert("missing date or time element");
} else {
date = dateTime[0].split("-");
if (date.length !== 3) {
alert("incorrect number of date elements");
} else {
value = +date[0];
if (date[0].length !== 4 || value < -9999 || value > 9999) {
alert("year value is incorrect");
}
value = +date[1];
if (date[1].length !== 2 || value < 1 || value > 12) {
alert("month value is incorrect");
}
value = +date[2];
if (date[2].length !== 2 || value < 1 || value > daysInGregorianMonth(+date[0], +date[1])) {
alert("day value is incorrect");
}
}
time = dateTime[1].split(":");
if (time.length !== 3) {
alert("incorrect number of time elements");
} else {
value = +time[0];
if (time[0].length !== 2 || value < 0 || value > 23) {
alert("hour value is incorrect");
}
value = +time[1];
if (time[1].length !== 2 || value < 0 || value > 59) {
alert("minute value is incorrect");
}
value = +time[2];
if (time[2].length !== 2 || value < 0 || value > 59) {
alert("second value is incorrect");
}
}
}
}
console.log(userDate);
console.log(today);
jsFiddle
Checking yyyy-mm-dd hh:mm:ss strings against each other is pretty easy because they're already in order; you can forget about what base the numbers are in and simply do < or > as in string comparison. This may not work with other dates.
function compISOZDate(d1, d2) { // d1 is
if (d1 < d2) return -1; // smaller
if (d1 === d2) return 0; // the same
/* else */ return 1; // bigger
}
Validating dates is a bit more complicated, because the number of days in months can change. You can ignore this fact and just test for digits, but I prefer meeting half way, introducing upper limits.
function verifyMyDate(d) {
var re = /^\d{4}-(0[1-9]|1[0-2])-([0-2]\d|3[01]) (0\d|1[01]):[0-5]\d:[0-5]\d$/;
// yyyy - MM - dd hh : mm : ss
return re.test(d);
}
So for example using it
var d1 = '2013-10-07 11:58:26',
d2 = '2012-06-14 19:22:03';
// check
if (!verifyMyDate(d1)) throw new Error('Invalid date: ' + d1);
if (!verifyMyDate(d2)) throw new Error('Invalid date: ' + d2);
// compare
compISOZDate(d1, d2); // 1, d1 is bigger than d2
// also
compISOZDate(d2, d1); // -1
compISOZDate(d1, d1); // 0
Now all that is left is to get the value from your inputs.
Change your RegExp inside the ValidateDate function to below code
function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/\b\d{4}[\/-]\d{1,2}[\/-]\b\d{1,2} (0\d|1[01]):[0-5]\d:[0-5]\d$\b/);
return dtRegex.test(dtValue);
}
try this and let me know, same way u can validate the hh:mm:ss also
For 24 hour variation, instead of AM/PM, use:
regex = new RegExp(^\d{4}-(0[1-9]|1[0-2])-([0-2]\d|3[01]) (0\d|1\d|2[0-3]):[0-5]\d:[0-5]\d$);
This is mine I wrote and works fine :
function validateDate(dtValue) {
// Format expected dd/mm/aaaa or dd-mm-aaaa (French Date)
// Accept also d/m/aaaa or d-m-aaaa (ok for MySQL Database to have one number only for days and months)
// Before the insert into database I will convert to aaaa-mm-jj or aaaa-m-j
var dtRegex = new RegExp(/\b(0?[1-9]|([1-2]?[0-9]|3[0-1]))[\/-]([0]?[1-9]|1[0-2])[\/-]\b\d{4} ([0-1]?[0-9]|2[0-3]):[0-5]\d$\b/);
// Accept range => (01 to 31) (/ or -) (01 to 12) (/ or -) (4 numbers) space (00 to 23) : (00 to 59)
var bValidateDate= dtRegex.test(dtValue);
// Test if bValidateDate true, test and throw out (accepted from regex expression) :
// 30/02, 31/02, 31/04, 31/06, 31/09, 31/11
// 30-02, 31-02, 31-04, 31-06, 31-09, 31-11
// Get the 5 first characters
var sFebruary29= dtValue.substring(0, 5);
if (bValidateDate)
{
var aOfDateErrors= ["30/02", "31/02", "31/04", "31/06", "31/09", "31/11", "30-02", "31-02", "31-04", "31-06", "31-09", "31-11"];
if (aOfDateErrors.indexOf(sFebruary29) > -1)
{
bValidateDate= false;
}
}
// Then, if bValidateDate is still true (good format)
// check if the date is a leap year to accept 29/02 or 29-02
// And finally, my customer asked me to have a year between 2017 and now
if (bValidateDate)
{
// Get the year
var sYear= dtValue.substring(6, 10);
// Customer's constraints
var bYearCustomerOK= ((parseInt(sYear) >= 2017) && (parseInt(sYear) <= new Date().getFullYear()));
// I promise, this is the "last test'em all !"
var bFinalDate= (bYearCustomerOK) && (sYear % 400 === 0 || sYear % 100 !== 0 && sYear % 4 === 0) && ((sFebruary29 == "29/02") ||(sFebruary29 == "29-02"));
if (! bFinalDate)
{
bValidateDate= false;
}
}
return bValidateDate;
}
Please, let me know if you find a bad date :)

substring javascript and html

<script>
function myFunction(){
//Example I passed in 31-02-2013
//var timeDate = document.getElementById('date').text; <--This Wont Work!
//This is some very basic example only. Badly formatted user entry will cause all
//sorts of problems.
var timeDate = document.getElementById('date').value;
//Get First 2 Characters
var first2 = timeDate.substring(0,2);
console.log(first2);
var dateArray = timeDate.split("-");
console.log(dateArray[0]);
var date = parseInt(dateArray[0], 10) ;//Make sure you use the radix otherwise leading 0 will hurt
console.log(date);
if( date < 1 || date > 30 )
alert( "Invalid date" );
var month2 = timeDate.substring(3,5);
console.log( month2 );
var monthArray = timeDate.split( "-" );
console.log( monthArray[1] );
var month = parseInt( monthArray[1],10 );
console.log( month );
if( month < 1 || month > 12 )
alert( "Invalid month" );
}
</script>
My function is working, just i want to some correction like if user input
-23-11-2013 // <--This won't work as the first alphabet is "-"
My text input only accept the date that
23-11-2013 // <---Will Work.
but for my function if i insert the date like -23-11-2013
it will show invalid month . what should i do some changes for my function
Check the javascript substring function here
My example : results in est
var a ="test";
console.log(a.substring(1));
Try this...
var date = "-23-11-2013";
data = date.split("-");
if(data.length == 3){
if(Number(data[0])>31){
alert("invalid date format");
}else if(Number(data[1])>12){
alert("invalid month format");
}
}else{
alert("incorrect format");
}
He is a better function you could perhaps use:
function myFunc(s) {
s = s.split("-").filter(Number);
return new Date(s[2], s[1], s[0]);
}
It should either return Invalid Date or a Date object.
So a call like myFunc("23-11-2013") or myFunc("-23-11-2013") should return a Date object:
Mon Dec 23 2013 00:00:00 GMT+0530 (India Standard Time)
Here is a better function that you can use:
function myFunction(date) {
var args = date.split(/[^0-9]+/),
i, l = args.length;
// Prepare args
for(i=0;i<l;i++) {
if(!args[i]) {
args.splice(i--,1);
l--;
} else {
args[i] = parseInt(args[i], 10);
}
}
// Check month
if(args[1] < 1 || args[1] > 12) {
throw new Error('Invalid month');
}
// Check day (passing day 0 to Date constructor returns last day of previous month)
if(args[0] > new Date(args[2], args[1], 0).getDate()) {
throw new Error('Invalid date');
}
return new Date(args[2], args[1]-1, args[0]);
}
Pay attention that month in Date constructor is 0 based and you need to subtract 1 from actual value. Besides of it you have wrong day check since different months have different number of days. Provided function also allows to pass values like -23 - 11/2013 with spaces and special characters, the only thing matters is the order of numbers (day, month, year).
Here you can see it working http://jsbin.com/umacal/3/edit

How to validate date user input in javascript on mm:dd:yy format

I tried validating date with the following code:-
function d(id){
var n= document.getElementById(id);
var re=/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/;
if (re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("Invalid date");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
But it isn't working. What is the problem with this code?
try this
function isValidDate(subject){
if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
return true;
}else{
return false;
}
}
Try to use this function
function isDate(txtDate, separator) {
var aoDate, // needed for creating array and object
ms, // date in milliseconds
month, day, year; // (integer) month, day and year
// if separator is not defined then set '/'
if (separator === undefined) {
separator = '/';
}
// split input date to month, day and year
aoDate = txtDate.split(separator);
// array length should be exactly 3 (no more no less)
if (aoDate.length !== 3) {
return false;
}
// define month, day and year from array (expected format is m/d/yyyy)
// subtraction will cast variables to integer implicitly
month = aoDate[0] - 1; // because months in JS start from 0
day = aoDate[1] - 0;
year = aoDate[2] - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert input date to milliseconds
ms = (new Date(year, month, day)).getTime();
// initialize Date() object from milliseconds (reuse aoDate variable)
aoDate = new Date();
aoDate.setTime(ms);
// compare input date and parts from Date() object
// if difference exists then input date is not valid
if (aoDate.getFullYear() !== year ||
aoDate.getMonth() !== month ||
aoDate.getDate() !== day) {
return false;
}
// date is OK, return true
return true;
}

validate javascript date

Is there a fast way to validate that a date/time in this format is valid?
I would prefer not to breaking it down with substrings and rebuilding it if possible
"YYYY-MM-DD HH:MM:SS"
You could parse the date string as an ISO string (by converting the space to a "T" and appending the Zulu timezone, e.g. "2011-08-16T12:34:56Z") then compare the resulting date's ISO string to the original ISO string.
function isValidDateString(s) {
try {
var isoStr = (""+s).replace(/ /,'T') + "Z"
, newStr = new Date(isoStr).toISOString();
return isoStr.slice(0,19) == newStr.slice(0,19);
} catch (e) {
return false;
}
}
This way, if the date string has invalid format, then the string "Invalid Date" will not equal the original and if it were to roll (e.g. if the day was invalid for the month) then the string value of the parsed date will not equal the original string.
[Edit]
Note the changes to the example code required by the timezone fix.
Try a regular expression like this.
Edit: Here is the string you'll want to match against:
^([1-3][0-9]{3,3})-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2][1-9]|3[0-1])\s([0-1][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9])$
You can use this regex.
/^([0-9]{4})-([0-1][0-9])-([0-3][0-9])\s([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/.test("2007-08-04 18:01:01"); //true
/^([0-9]{4})-([0-1][0-9])-([0-3][0-9])\s([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/.test("2007-08-04 18:01:0"); //false
The following code below will check to see if the date input is actually a valid date.
At first glance it looks big, but it's mostly the comments.
It requires no substrings and no regular expression.
The way JavaScript works is that, if you break down a Date object with an invalid date (04/32/2010) to it's total milliseconds and then create another Date object with those milliseconds, it will not create a Date object that displays the incorrect date (04/32/2010) it will compensate and create the proper Date (05/01/2010).
So simply, if the input is different than the new Date object, then the date is not valid.
http://jsfiddle.net/dceast/vmHjN/ - Here is an example of it on JSFiddle.
var compareDate, checkDates = false;
var validateObject = {
init: function(year, month, day) {
return this.compareDate.init(year, month, day);
},
compareDate: {
init: function(year, month, day) {
var isValid = false;
// Compensate for zero based index, if month was not
// subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
month -= 1;
// Create a new date object with the selected
// year, month, and day values and retrieve the
// milliseconds from it.
var mSeconds = (new Date(year, month, day)).getTime();
var objDate = new Date();
// Set the time of the object to the milliseconds
// retrieved from the original date. This will
// convert it to a valid date.
objDate.setTime(mSeconds);
// Compare if the date has changed, if it has then
// the date is not valid
if (objDate.getFullYear() === year &&
objDate.getMonth() === month &&
objDate.getDate() === day)
{
isValid = true;
}
return isValid;
}
}
};
I did so and it worked
<html>
<head>
<title>valida data</title>
<script>
function valData(data){//dd/mm/aaaa
day = data.substring(0,2);
month = data.substring(3,5);
year = data.substring(6,10);
if( (month==01) || (month==03) || (month==05) || (month==07) || (month==08) || (month==10) || (month==12) ) {//months 31 days
if( (day < 01) || (day > 31) ){
alert('invalid date');
}
} else
if( (month==04) || (month==06) || (month==09) || (month==11) ){//months 30 days
if( (day < 01) || (day > 30) ){
alert('invalid date');
}
} else
if( (month==02) ){//February and leap year
if( (year % 4 == 0) && ( (year % 100 != 0) || (year % 400 == 0) ) ){
if( (day < 01) || (day > 29) ){
alert('invalid date');
}
} else {
if( (day < 01) || (day > 28) ){
alert('invalid date');
}
}
}
}
</script>
</head>
<body>
<form>
<input type="text" name="data" id="data" onBlur="return valData(this.value)" />
</form>
</body>
</html>

Categories

Resources