Link to home
Start Free TrialLog in
Avatar of marc_butler
marc_butler

asked on

JavaScript ValidateDate UK

Hi All,

I have a very simple function to validate a date, but it is in US can anyone change it to UK format for me please.
function ValidateDate(str)
{
	// make sure it is in the expected format
	if (str.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
		return false;
	
	// remove other separators that are not valid with the Date class
	str = str.replace(/[\-|\.|_]/g, "/");
	
	// convert it into a date instance
	var strDate = new Date(Date.parse(str));
	
	// check the components of the date
	// since Date instance automatically rolls over each component
	var arrDateParts = str.split("/");
		return (strDate.getMonth() == arrDateParts[0]-1 && strDate.getDate() == arrDateParts[1] && strDate.getFullYear() == arrDateParts[2]);
}

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image


function ValidateDate(str)
{
        // make sure it is in the expected format
        if (str.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
                return false;
        
        // remove other separators that are not valid with the Date class
        str = str.replace(/[\-|\.|_]/g, "/");
        
        // convert it into a date instance
        var strDate = new Date(Date.parse(str));
        
        // check the components of the date
        // since Date instance automatically rolls over each component
        var arrDateParts = str.split("/");
                return (strDate.getDate() == arrDateParts[1] && strDate.getMonth() == arrDateParts[0]-1 && strDate.getFullYear() == arrDateParts[2]);
}

Open in new window

Avatar of marc_butler
marc_butler

ASKER

Hi hielo,

I don't think the problem is the return. Ithink its the str.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0) as the results are false at the other end.

I think the problem is the search string?
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hielo,

Thank you very much for the help, works like a charm.