PDA

View Full Version : Resolved validate date format (y/m/d)



vineet
12-10-2008, 06:13 AM
hi all

i want to use a function to format date in (yyyy/mm/dd).
The function is in my below code. how can i call this function onChange or onBlur so that when the user enters date it should alert if the date format is not valid.



<html>
<head>
<script language="javascript">
function validDate(y,m,d)
{
if (y != parseInt(y,10) || m != parseInt(m,10)
|| d != parseInt(d,10)) return false;
m--;
var nd = new Date(y, m, d);
if (y == nd.getFullYear() && m == nd.getMonth()
&& d == nd.getDate()) return nd;
else return false;
}
var customer_dob = validDate(year, month, day);
if (!customer_dob)
{
alert('the date entered is invalid');
}
</script>
</head>
<body>
<form action="" method="get" name="advertise">
<input type="text" name="customer_dob" onChange="return validDate();" />
</form>
</body>

Snookerman
12-10-2008, 09:39 AM
I found a script and rewrote it a bit to fit your requirements. It is a bit more advanced since it checks for leap years (even checks if they are divisible by 400 (http://en.wikipedia.org/wiki/Leap_years#Gregorian_calendar)). Here is the code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language = "Javascript">
/**
* DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring valid date character, minimum year and maximum year
// Changed by Snookerman into yyyy/mm/dd format
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}

function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}

function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strYear=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strDay=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : yyyy/mm/dd")
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}

function ValidateForm(){
var dt=document.frmSample.txtDate
if (isDate(dt.value)==false){
dt.focus()
return false
}
return true
}

</script>
</head>
<body>
<form name="frmSample" method="post" action="" onSubmit="return ValidateForm()">
<p>Enter a Date <font color="#CC0000"><b>(yyyy/mm/dd)</b></font> :
<input type="text" name="txtDate" maxlength="10" size="15">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>

The original code is taken from here:

http://www.smartwebby.com/DHTML/date_validation.asp (http://www.smartwebby.com/DHTML/date_validation.asp)

I just changed it to your format, yyyy/mm/dd.

vineet
12-10-2008, 12:44 PM
hi Snookerman

thanks a lot. it worked great. its really advanced script.

vineet

Snookerman
12-10-2008, 01:54 PM
You're welcome! Make sure you mark this thread as Resolved.

boogyman
12-10-2008, 05:14 PM
If you wanted just to check whether the date was entered in a valid format, you could use the following



<script type="javascript">
function checkDateFormat(field)
{
/* What will be separating the values */
var delimiter="/";
/* Message to display if date format is incorrect */
var msg = "The date you entered, appears to be in an incorrect format.";

/********************************
** no need to edit beyond this line **
********************************/
var el = document.getElementById(field);

/* checks if delimiter is regexp "wildcard" */
if(/[-./].test(delimiter))
delimiter = "\"+delimiter;

/* yyyy(delimiter)mm(delimiter)dd */
var format = "/^[(19)|(20)]\d{2}"+delimiter+"[0-3]?[0-9]"+delimiter+"[0-3]?[0-9]$/";

/* if error message already exists */
var errMsg = document.getElementById('errMsg');
if(errMsg);
el.removeChild(errMsg);

/* if doesn't follow format, writes error message */
if(!format.test(el))
{
var p = document.createElement('p');
p.id="errMsg";
p.style.color = "#ff0000";
p.style.font-weight = "bold";
p.nodeValue = msg;
el.appendChild(p);
}
}
</script>




<input type="text" name="f_date" value="" onchange="javascript:checkDateFormat(this);">


If entered incorrectly, will produce the following with the example message
The date you entered, appears to be in an incorrect format.

vineet
12-11-2008, 05:55 AM
hi boogyman

i think something is missing in your code.

i pasted it and half of the script is coming in original javascript code color and rest bottom half is coming in single blue colour.

vineet

boogyman
12-11-2008, 02:11 PM
change


delimiter = "\"+delimiter;

to


delimiter = "\\"+delimiter;

the first backslash was escaping the end quotation

vineet
12-11-2008, 03:01 PM
hi boogyman

This is complete code with correction which is giving error.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
function checkDateFormat(field,delimiter)
{
/* What will be separating the values */
var delimiter="/";
/* Message to display if date format is incorrect */
var msg = "The date you entered, appears to be in an incorrect format.";

/********************************
** no need to edit beyond this line **
********************************/
var el = document.getElementById(field);

/* checks if delimiter is regexp "wildcard" */
if(/[-./].test(delimiter))
delimiter = "\\"+delimiter;

var format = "/^[(19)|(20)]\d{2}"+delimiter+"[0-3]?[0-9]"+delimiter+"[0-3]?[0-9]$/";

if(!format.test(el))
{
var p = document.createElement('p');
p.style.color = "#ff0000";
p.style.font-weight = "bold";
p.nodeValue = msg;
el.appendChild(p);
}
}
</script>
</head>
<body>
<form name="form1" method="post" action="">
<p>Enter a Date <font color="#CC0000"><b>(yyyy/mm/dd)</b></font> :
<input type="text" name="f_date" value="" onchange="javascript:checkDateFormat(this);">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>


This is the error its giving


Line:20
Char:31
Error: Expected '/'
Code:0


its not alerting

vineet

Snookerman
12-11-2008, 03:20 PM
Is the code I posted working for you?

vineet
12-12-2008, 03:04 AM
Is the code I posted working for you?

hi snookerman

yes the code you posted is working for me.

i m just telling boogyman that his code has some errors.

otherwise our issue has been resolved.

vineet

rangana
12-12-2008, 06:06 AM
There are few typos from boogy's code:


Let's start from the one boogyman himself found:

change
to

delimiter = "\\"+delimiter;
the first backslash was escaping the end quotation


The type value should be text/javascript:


<script type="javascript">



The RegEx is erroneous:


if(/[-./].test(delimiter))


...should be:


if(/[-.]/.test(delimiter))



The RegEx should not be treated as string:


var format = "/^[(19)|(20)]\d{2}"+delimiter+"[0-3]?[0-9]"+delimiter+"[0-3]?[0-9]$/";


...removing highlighted should fix.


To assign font-weight property via JS, it should be:


p.style.fontWeight = "bold";


...instead of:


p.style.font-weight = "bold";



There are yet some more problems, but basically those are the basics.