...

View Full Version : Date format



timgolding
02-21-2007, 03:52 PM
Hi

I am creating a site for a friend to manage his tax returns. The thing I need help with is a validator function thats checks the format of an input field. The input fields are simple textboxes. They are for recording dates but entry must be in the format of dd-mm-yy e.g. 21-01-07

I wanted a script to be triggered for onchange event. This is where it will be validated. I hoped to use a regex to test it or something (if possible in js) then if validation fails the box with be cleared and an alert message will be displayed. I am not very experienced with js and would appreciate some help.

timgolding
02-21-2007, 04:19 PM
This is how far i have got


function validate(obj){
var el = document.getElementById(obj);
if(!(/^\d{2}-\d{2}-\d{2}/.test(el.value)))
{
el.value='';
el.focus();
alert('Date format must be dd-mm-yy e.g. 21-02-07');
}
}


Problem is it only checks if two digits are present if I can prevent users from adding something like 99-99-99 that would be great

timgolding
02-22-2007, 09:13 AM
Any ideas?

Philip M
02-22-2007, 11:01 AM
function validate(obj){
var el = document.getElementById(obj);
var failFlag=0;
if(!(/^\d{2}-\d{2}-\d{2}/.test(el.value))) {
failFlag=1; // wrong format
}
var ss=el.split("-");
if (ss[0] <1 || ss[0] >31) {failFlag=1} // day
if (ss[1] <1 || ss[1] >12) {failFlag=1} // month
if (ss[2] <0 || ss[2] <15) {failFlag=1} //max year 2015
if (failFlag==1) {
el.value='';
el.focus();
alert('Date format must be dd-mm-yy e.g. 21-02-07');
}
}

This still does not check for invalid dates such as 30th February.

timgolding
02-22-2007, 11:10 AM
Thank you so much you're a wonderful person :)

timgolding
02-22-2007, 01:57 PM
This script isnt working I am getting an error with the split function

el.split is not a function

Any idea why?

BarrMan
02-22-2007, 02:57 PM
Add .value after the el:

var ss=el.value.split("-");

Edit:
One more thing, replace this:

if (ss[2] <0 || ss[2] <15) {failFlag=1} //max year 2015
With this:

if (ss[2] <0 || ss[2] >15) {failFlag=1} //max year 2015



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum