View Full Version : regex validation problem

08-22-2008, 09:50 PM
I am trying to validate some form input with the following javascript regex. This is data that is to be submitted to an XML webservice so the date string MUST be in one of the allowed formats.

I can validate all of the allowed formats however it also validates mm/dd/yyyy as being good.
Can anyone help me with this.

function validateDateFormat(fldName,fldValue){
var regex = /^([0][1-9]|[1][1-2])\/(20[0-9]{2}|19[0-9]{2})|(20[0-9]{2}|19[0-9]{2})|([0][1-9]|[1][1-2])\/([0-9]{2})|([0][1-9]|[1][1-2])\/([0-2][0-9]|[3][0-1])\/([0-9]{2})$/;
var error = "";
if(! regex.test(fldValue)){
error = "- "+fldName+" must be entered as yyyy or mm/yyyy or mm/dd/yy or mm/yy.\n";
return error;

08-22-2008, 10:58 PM
It looks like that is what you want isn't it
must be entered as yyyy or mm/yyyy or mm/dd/yy or mm/yy. Never mind I didn't notice the extra y's

08-22-2008, 11:10 PM
yyyy = Good
mm/yyyy = Good
mm/yy = Good
mm/dd/yy = Good

mm/dd/yyyy = BAD :(

Philip M
08-23-2008, 08:48 AM
There is no point is trying to validate using just one complicated regex test:-

<input type = "text" id = "fldValue" onblur = "checkDate()">

<script type = "text/javascript">

function checkDate () {
var x = document.getElementById("fldValue").value;
var flag = 0;
if (/^(20[01]\d)$/.test(x)) {flag = 1} // year 200x or 201x
if (/^0[1-9]|^(11)|^(12)\/(20)?[01]\d$/.test(x)) {flag = 1} // mm/yyyy or mm/yy
if (/^0[1-9]|^(11)|^(12)\/[0-3]\d\/[01]\d$/.test(x)) {flag = 1} // mm/dd/yy

if (flag == 1) {
alert ("The date is in valid format");
else {
alert ("The date is NOT in valid format");



Valid years are 200x or 201x, or 0x or 1x.
Note that this does not check that the day is allowable for the month (e.g. 31st February)

The Moving Finger writes; and, having writ,
Moves on: nor all your piety nor wit
Shall lure it back to cancel half a line,
Nor all your tears wash out a word of it.

-- Omar Khayyam

08-23-2008, 06:19 PM
good idea I will break the validation up.

I wasn't validating that it is a good date. I am just ensuring that when the data is ran in the webservice that this does not break the XML schema that this data has to go into.