0

How to validate date in yyyy-mm-dd format using javascript. so far i have come up with this code.

<script>  
  function checkdate(form)  
  {  
   var a = document.forms["form"]["stdt"].value; 


    Check = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/; 
    if(!a.match(Check)) {  
     alert("Error: Date format: ##-##-#### ");  
     return false;  
    }  

   }   
</script>

and HTML code

<form id="myform" onsubmit="return checkdate(this);"  method="post" action="">

The above will return true for 11-55-1999

7
  • 1
    So title says YYYY-MM-DD and your question says MM-DD-YYYY. So what is it? Commented Aug 24, 2016 at 12:42
  • (1[012]|0[1-9]) will match the numbers 01..12. Commented Aug 24, 2016 at 12:42
  • Check = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/; if(!a.match(Check)) { alert("Error: Date format: ####-##-## "); i tried this also but the result is same Commented Aug 24, 2016 at 12:43
  • 3
    Regular expression for date checking is not the best bet. leap years, does the month have 31 days, etc. Commented Aug 24, 2016 at 12:44
  • ^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$ try this regex Commented Aug 24, 2016 at 12:44

2 Answers 2

1

I use moment, read the docs here http://momentjs.com/

It is simple to use, you have a value

var dateExample = '2016-08-23T16:09:11.690Z';
var DATE_FORMAT = 'YYYY/MM/DD';    
moment(dateExample).format(DATE_FORMAT)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Jquery vaidation for that as below

$('#frm').validate({
      rules: {
           date_creation: {
               required: true,
               date: true
           }
      }
   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.