substring javascript and html - javascript

<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

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 to test the Date, Month and Year entered as 2 Digits are valid?

In my form, a user can enter the date like this: 220875 (day, month, year).
Once they entered the details, I would like to test that the date is valid:
Month is from 1 to 12 inclusive.
The day entered is valid for the specified month.
How would I find out whether or not the values are correct and matching?
here is my attempt: (excerpt)
DateIsOk:function(value) { //220875 for example
var formatValue = value.match(/.{1,2}/g), //splting as 22 08 75
fieldDate = parseInt(formatValue[0]), //converting to num
fieldMonth = parseInt(formatValue[1]),
fieldYear = parseInt(formatValue[2]),
dayobj = new Date();
//test need to go here...
}
If it helps, here is a Live Demo.
It seems you use the DD/MM/YYYY format.
So you can easily use this ready-to-use code: http://www.qodo.co.uk/blog/javascript-checking-if-a-date-is-valid/
JavaScript
// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(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;
}
}
If you don't mind using momentjs as #hVostt suggested, you could try modifying your DateIsOk() validation function like this:
...
dateParts : ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"],
DateIsOk:function(value) {
var dayobj = moment(value, "DDMMYY");
if (dayobj.isValid()) {
this.errorHandler(true);
return true;
}
else {
this.errorHandler('Invalid ' + this.dateParts[dayobj.invalidAt()]);
return false;
}
}
...
Here's the updated Live Demo
The js regexp maybe like this
/([0-2][0-9]|3[01])(0[1-9]|1[0-2])(\d{2})/
Please try Moment.js and his validation functions:
http://momentjs.com/docs/#/parsing/is-valid/
moment([2014, 25, 35]).isValid();
moment("2014-25-35").isValid();

JSP Date validation

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;
}
}

javascript date validation not validation February 31

I am trying to write some code with will validate form data. I have a date field which should have a mm/dd/yyyy format. I needed to catch exceptions such as February 31, so I added this code:
var d = new Date(dob);
if (isNaN(d.getTime())) { //this if is to take care of February 31, BUT IT DOESN'T!
error = 1;
message += "<li>Invalid Date</li>";
} else {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var validFormat = date_regex.test(dob);
if (!(validFormat)) {
error = 1;
message += "<li>Invalid date format - date must have format mm/dd/yyyy</li>";
}
}
However I found something very weird: while the date 02/32/2000 errors as an invalid date, 02/31/2000 does not!
Due to what I said in the comments...
Another way you could check if a date is valid is by checking whether or not the stuff you passed into the new Date function is the same as what comes out of it, like this:
// Remember that the month is 0-based so February is actually 1...
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
then you could do this:
if (isValidDate(2013,1,31))
and it would return true if valid and false if invalid.
After wrecking my head with the obscurity of Date .getMonth() (and also weekday by .getDay()) being 0-index (despite year, day and all the others not being like so... oh god...) I've re-wrote Jeff's answer to make it more readable and more friendly-usable to whom consume the method from outside.
ES6 code
You can call passing month as 1-indexed as you'd normally expect.
I've parsed inputs using Number constructor so I can use strict equality to more confidently compare values.
I'm using the UTC version methods to avoid having to deal with the local timezone.
Also, I broke steps down into some variables for the sake of readability.
/**
*
* #param { number | string } day
* #param { number | string } month
* #param { number| string } year
* #returns { boolean }
*/
function validateDateString(day, month, year) {
day = Number(day);
month = Number(month) - 1; //bloody 0-indexed month
year = Number(year);
let d = new Date(year, month, day);
let yearMatches = d.getUTCFullYear() === year;
let monthMatches = d.getUTCMonth() === month;
let dayMatches = d.getUTCDate() === day;
return yearMatches && monthMatches && dayMatches;
}
Are you able to use a library?
My first port of call for date handling in Javascript is moment.js: "A javascript date library for parsing, validating, manipulating, and formatting dates."
The ususal way to validate a 'mm/dd/yyyy' date string is to create a date object and verify that its month and date are the same as the input.
function isvalid_mdy(s){
var day, A= s.match(/[1-9][\d]*/g);
try{
A[0]-= 1;
day= new Date(+A[2], A[0], +A[1]);
if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
isvalid_mdy('02/31/2000')
/* returned value: (Error)Bad Date */
Assuming month input is 1-12 (1-based, not 0-based):
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day);
return month == d.getMonth() + 1;
}
isValidDate(2019, 12, 0); //=> false
isValidDate(2020, 2, 29); //=> true
isValidDate(2021, 2, 29); //=> false
isValidDate(2022, 2, 31); //=> false
Basically an alternative to the above-mentioned examples
function (date) {
if (!/(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([1-2][0-9]{3})/g.test(date))
{
alert('Incorrect date format please follow this form: dd/mm/yyyy');
return;
}
else
{
// secondary validation
const parts = (date).split('/').map((p) => parseInt(p, 10));
let day = Number(parts[0]);
let month = Number(parts[1]) - 1; // 0-indexed month
let year = Number(parts[2]);
let d = new Date(year, month, day);
if (!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day))
{
alert('Incorrect date, please enter the correct day entry');
return;
}
}
}
I may be a little late for posting an answer but here is what worked best for me
var user_date = (`${user_values.month_value} ${user_values.date_value} , ${user_values.year_value}`)
const d = new Date(user_date);
let day = d.getDate()
if(user_values.date_value != day){
setdate_validation({
display:'flex'
})
}
else{
setdate_validation({
display:'none'
})
console.log(user_values)
so in the above code what happens is i get different inputs from my user like one dropdown for date another for month and so on , i collect them and store it with .getdate() now .getdate() function returns the value of day , so if i stored (02 21 , 2002) then the .getdate() will return 21 ,
but there is a catch if i enter an invalid date like (02 30, 2002) where 30 is invalid in month of february then the .getdate() function returns not the same date but the date in next month or increment as much you are far away from a valid date like if 28 is valid and I entered 29 then .getdate() will show 1 as the output so i just compare the result of .getdate() with my current date value which is entered and if it is not same then the date is invalid.
(this code is from react using usestates)

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