0
var chkdate=document.getElementById('date');
var dateformat=/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01]){2}/;

if(!dateformat.test(chkdate.value))
{
    alert("Please format the date in yyyy-mm-dd format.");
    return false;
}

and the html:

<form name="test" action="" onsubmit="return validateForm()" method="post">
Name: <input type="text" placeholder="First Last" name="name" id="name"><br />
Date: <input type="text" placeholder="yyyy-mm-dd" name="date" id="date"><br />
Number: <input type="integer" placeholder="Any integer/decimal" name="number" id="number"><br /><br />
<input type="submit" value="Submit">

The validation works in the format yyyy-mm, however the day allows you to enter any number of numbers at the end. I.e 2013-06-14444444444 would get passed through. I want to restrict it purely to JUST yyyy-mm-dd. How would I go above achieving this?

SirReich
  • 3
  • 1
  • 1
    I'd recommend you think about using a more robust solution, not just a regex. How about `2013-11-31`. That would be valid according to regex but it isn't a valid date. Check this answer http://stackoverflow.com/questions/11218181/best-way-to-validate-date-string-format-via-jquery/11218271#11218271 – elclanrs Jun 14 '13 at 20:25

3 Answers3

2

Add '$' sign at the end that matches the end-of-line:

var dateformat=/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01]){2}$/;
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

update the pattern line by adding a $ at the end to specify that this is where the pattern ends:

var dateformat=/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01]){2}$/;
naivists
  • 32,681
  • 5
  • 61
  • 85
0

Just adding a $ at the end won't completely fix it, as you also have a {2} which is letting the last capture group repeat itself so instead of yyyy-mm-dd it is checking yyyy-mm-ddxx, xx like dd.

/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01]){2}$/
    .test('2013-06-1414');   // true, wait what?

Simply remove it to fix

var re = /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/;

re.test('2013-06-1414');     // false
re.test('2013-06-14');       // true
Paul S.
  • 64,864
  • 9
  • 122
  • 138