...

View Full Version : Help with regular expressions



futurecoder12
10-04-2011, 08:52 PM
Hi everyone,

I am trying to validate a date by using regular expressions.
I have parts working, such as only accepts numbers, but I cannot get the range correct. On the "mm" field, I am getting errors.



if(form.mm.value=="")

{
alert("Please insert your birth month");
return false;}
var re=/^(0[1-9]|1[0-2]){2}$/;
if(!re.test(form.mm.value))
{
alert("Please fix birth month!");
return false;
}
{
if(form.dd.value=="")

{
alert("Please insert your birth day");
return false;}
var re=/^\d{2}$/;
if(!re.test(form.dd.value))
{
alert("Please fix birth day!");
return false;
}
{
if(form.yyyy.value=="")

{
alert("Please insert your birth year");
return false;}
var re=/^\d{4}$/;
if(!re.test(form.yyyy.value))
{
alert("Please fix birth year!");
return false;


Any suggestions will be greatly appreciated.

Philip M
10-04-2011, 10:12 PM
var re=/^(0[1-9])$|^(1[0-2])$/;


var re=/^\d{2}$/; // but what about birthdays 1st - 9th?

var re=/^\d{4}$/; // 4782???

I would not try to use regular expressions here - just check day is in numeric range 1-31, month is in numeric range 1-12, year is sensible (say 1911 - 2011). But what if the user enters say 31/02/2009?

You need to check that the date entered is in fact a valid date.


<script type = "text/javascript">

function checkValidDate(yr,mmx,dd) {

if (yr <1910 || yr >2010) { // you may want to change 2010 to some other year!
alert ("Impossible Year Of Birth!")
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date();
nd.setFullYear(yr,mm,dd); // format YYYY,MM(0-11),DD

var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
}
}

checkValidDate(2010,2,31) // 31st February 2009
</script>




His [Andy Murryay's] balls are 10 to 15% heavier now than at the start - Tennis commentator Radio5 Live



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum