Jump to content

Help. Date validation with JavaScript

Go to solution Solved by Mr_KoKa,
function validateDate(date){
	if(date.match(/^\d{4}-\d{2}-\d{2}$/)){
		var dateTime;
		if(!isNaN((dateTime = Date.parse(date + ' 00:00:00')))){
			var now = new Date();
			now.setHours(0);
			now.setMinutes(0);
			now.setSeconds(0);
			now.setMilliseconds(0);
			
			now = now.getTime();
			
			var minDiff = 1000 * 60 * 60 * 24 * 2;
			var diff = dateTime - now;
			
			if(diff >= minDiff){
				return true;
			} else {
				alert('Entered date has to be 2 days ahead current date.');
			}
		} else {
			alert('Wrong value.');
		}
	} else {
		alert('Wrong format.');
	}
	
	return false;
}

What I did is parse date from the input to check if it is valid, because 2016-99-99 will match patter but won't be valid date, parse returns NaN in such case.

Notice that I added time string, I noticed that without it my date end up ahead of value of timezone, so my timezine is GMT +2 and when i entered 2016-10-30 I ended up with timestamp for datetime of 2016-10-30 02:00:00

 

So when date is valid, parse returns timestamp with milliseconds, then I create new Date object that defaults to current datetime, I reset hours, minutes, seconds and milliseconds to compare just dates, then I convert Date object to timestamp by calling getTime method and finally I calculate difference between entered and current date and compare it with the minimal difference.

I am in the process of making a validation function for a date. I need help figuring out how to make it not accept the date entered if the date is not for 2 days in advanced. So if today's date is 10/30/2016 an error should show up saying that the date has to be 2 days from today's date. (11/01/2016).

I will post just the section with the function and go from there. 

Thanks in advanced. 

var $ = function(id) 
{	return document.getElementById(id);	}//end $
window.onload = function() 
{
	$("theForm").reset(); //Clear previous entries in FF
	
		$("btnSubmit").onclick = validateForm;
		$("btnReset").onclick = resetForm;
	
	
	
		$("currentTime").innerHTML = (new Date).toLocaleString();
	
	
	$("txtCustName").required = true;
	$("txtCustName").onblur = validateUserName;
	
	
	$("txtTitle").required = true;
	$("txtTitle").onblur = validateBookTitle;
	
	$("cmbFormat").onblur = validateBookFormat;
	$("cmbFormat").required = true;
	
	
	$("txtPrice").min = 10;
	$("txtPrice").max = 100;
	$("txtPrice").required = true;
	$("txtPrice").onblur=validateQuotedPrice;
	
	
	$("txtQuantity").required = true;
	$("txtQuantity").onblur=validateQuanityOrdered;
	
	$("rdoDiscover").onclick = hidePaymentOptionError;
	$("rdoPayPal").onclick = hidePaymentOptionError;
	$("rdoVisa").onclick = hidePaymentOptionError;
	
	$("rdoDiscover").required = true;
	$("rdoPayPal").required = true;
	$("rdoVisa").required = true;
	
	$("rdoDiscover").onblur=validatePaymentOption;
	$("rdoPayPal").onblur=validatePaymentOption;
	$("rdoVisa").onblur=validatePaymentOption;
	
	
	$("dtpDelivery").required = true;
	$("dtpDelivery").onblur=validateDate;
	$("dtpDelivery").max="2017-12-31";
	$("dtpDelivery").min="2016-01-01";
}




function validateDate()
{
	var ptr = $("dtpDelivery");  //Pointer to input field
	var err = $("errDelivery");  //Pointer to field's error marker

	err.style.visibility = "visible";
	
	//Regular Expression for yyyy-mm-dd
	//2016-11-26    2016-10-31
	var patternForYyyyMmDd = /^\d{4}-\d{2}-\d{2}$/;
	if(ptr.value=="")
	{
		var enteredDate = ptr.value.replace(/[-\.]/g, "/");;
		if(isDate(enteredDate))
		{
			//Before checking range, make sure date is the right format
			if(!enteredDate.match(patternForYyyyMmDd))
			{
				//Reformat it
				enteredDate = new Date(enteredDate).format("yyyy-mm-dd");
			}//end if
			if(enteredDate < ptr.min || enteredDate > ptr.max)
			{
				err.title = "Date must be between " + ptr.min + " and " + ptr.max + ".";
			} 
			else 
			{
				err.style.visibility = "hidden";
				ptr.value = enteredDate;
			}//end if out of range
		}
		else
		{
			err.title = "This is not a recognizable date.";
		}//end if isDate
	}
//	else 
//	{
		//Display error if required
//	} //end if missing
	
	return err.style.visibility=="hidden";
}//end validateDate

 

Link to comment
Share on other sites

Link to post
Share on other sites

I can't really help you as I don't know javascript but what sort of program are you trying to make

Hello

Link to comment
Share on other sites

Link to post
Share on other sites

Actually it for an assignment I am working on. I have an Html file and an external JavaScript file. In the external Js File that is where I am building and calling the functions. I have other JS function files that I am "Importing" to use on the HTML page. If it helps I will upload what I have so far in a zip folder. Its ask for a name, book title, format, price, quantity, date,payment method, and total( still working on that also). 

Unit 10 - BookNook Validation (4).zip

Link to comment
Share on other sites

Link to post
Share on other sites

function validateDate(date){
	if(date.match(/^\d{4}-\d{2}-\d{2}$/)){
		var dateTime;
		if(!isNaN((dateTime = Date.parse(date + ' 00:00:00')))){
			var now = new Date();
			now.setHours(0);
			now.setMinutes(0);
			now.setSeconds(0);
			now.setMilliseconds(0);
			
			now = now.getTime();
			
			var minDiff = 1000 * 60 * 60 * 24 * 2;
			var diff = dateTime - now;
			
			if(diff >= minDiff){
				return true;
			} else {
				alert('Entered date has to be 2 days ahead current date.');
			}
		} else {
			alert('Wrong value.');
		}
	} else {
		alert('Wrong format.');
	}
	
	return false;
}

What I did is parse date from the input to check if it is valid, because 2016-99-99 will match patter but won't be valid date, parse returns NaN in such case.

Notice that I added time string, I noticed that without it my date end up ahead of value of timezone, so my timezine is GMT +2 and when i entered 2016-10-30 I ended up with timestamp for datetime of 2016-10-30 02:00:00

 

So when date is valid, parse returns timestamp with milliseconds, then I create new Date object that defaults to current datetime, I reset hours, minutes, seconds and milliseconds to compare just dates, then I convert Date object to timestamp by calling getTime method and finally I calculate difference between entered and current date and compare it with the minimal difference.

Link to comment
Share on other sites

Link to post
Share on other sites

Thanks Mr_KoKa I will go ahead and do the adjustments. Appreciate the time . 

Link to comment
Share on other sites

Link to post
Share on other sites

You can improve that code by passing the date you want to compare to as an argument, or even acceptable difference between them

function validateDate(dateToValidate, dateToCompareTo, difference) {
  ...
}
  
function daysToMiliseconds(days) {
  	return (24*60*60*1000)*days;
}

var isDateValid = validateDate('03/11/2016/', Date.now(), daysToMiliseconds(2));

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×