JavaScript Tutorial/Regular Expressions/Date

Материал из Web эксперт
Перейти к: навигация, поиск

Use Regular Expression to validate date

<html>
<head>
<title>Date Example</title>
<script type="text/javascript">
    function isValidDate(sText) {
        var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
        return reDate.test(sText);
    }
    function validate() {
        var oInput1 = document.getElementById("txt1");
        if (isValidDate(oInput1.value)) {
            alert("Valid");
        } else {
            alert("Invalid!");
        }
    }
</script>
</head>
<body>
    <P>Date: <input type="text" id="txt1" /><br />
    example: 05/05/2005<br />
    <input type="button" value="Validate" onclick="validate()" /></p>
</body>
</html>


Validate the Date

<HTML>
<HEAD>
<SCRIPT>
function checkDate(testStr) {
   var pattern = /\b(\d{2})\/(\d{2})\/(\d{4})\b/;
   var result = testStr.match(pattern);
   if (result != null)
      return "Well done.";
   else
      return "You didn"t input a date in the specified pattern.";
}
</SCRIPT>
</HEAD>
<BODY>
Check a date format today!
<FORM name="theForm">
Enter a date in mm/dd/yyyy format:
<INPUT type=text name=testStr size=20 maxlength=10>
<INPUT type=button 
       name="theButton" 
       value="Verify the Format"    
       onClick="alert(checkDate(document.theForm.testStr.value))";>
</FORM>  
</BODY>
</HTML>