Thursday, June 2, 2011

Javascript Date Validation function

<script language="javascript" >///^\d{5}$/.test('84601')



function IsValidDate(d) {var Day, Mn, Yr;var re = /^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})$/;
// var re = "^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$";
re.exec(d);
Yr = RegExp.$1;
Mn = RegExp.$2;
Day = RegExp.$3;




}

if (!d.match(re)) return false;var DateVal = Mn + "/" + Day + "/" + Yr;var dt = new Date(DateVal);if (dt.getDate() != Day) {return (false);else if (dt.getMonth() != Mn - 1) {//this is for the purpose JavaScript starts the month from 0
}


}

}
return (false);else if (dt.getFullYear() != Yr) {return (false);return (true);</script>




========================================
========================================


USAGE




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!
<
<
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 runat="server"><title></title><script language="javascript" >///^\d{5}$/.test('84601')


function IsValidDate(d) {var Day, Mn, Yr;var re = /^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})$/;// var re = "^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$";
re.exec(d);
Yr = RegExp.$1;
Mn = RegExp.$2;
Day = RegExp.$3;




}
if (!d.match(re)) return false;var DateVal = Mn + "/" + Day + "/" + Yr;var dt = new Date(DateVal);if (dt.getDate() != Day) {return (false);else if (dt.getMonth() != Mn - 1) {//this is for the purpose JavaScript starts the month from 0
}


}

}

</
<return (false);else if (dt.getFullYear() != Yr) {return (false);return (true);</script>head>body><form id="form1" runat="server"><div><input value="1999-9-9" id="datavalue" onblur="alert( IsValidDate(document.getElementById('datavalue').value) );"/></div>
</
</</form>body>html>

No comments:

Post a Comment