JavaScriptJavaScript 判斷輸入日期格式是否為 YYYY/MM/DD

JavaScript 日期格式檢查

判斷使用者輸入日期格式是否為 YYYY/MM/DD

forms when asking for date fields it is a good idea to validate the date value using client side JavaScript validation along with your programming language validation. The example shows how you can do this for the YYYY/MM/DD format.


JavaScript

function dateValidationCheck(str) {
  var re = new RegExp("^([0-9]{4})[./]{1}([0-9]{1,2})[./]{1}([0-9]{1,2})$");
  var strDataValue;
  var infoValidation = true;
  if ((strDataValue = re.exec(str)) != null) {
    var i;
    i = parseFloat(strDataValue[1]);
    if (i <= 0 || i > 9999) { /**/
      infoValidation = false;
    }
    i = parseFloat(strDataValue[2]);
    if (i <= 0 || i > 12) { /**/
      infoValidation = false;
    }
    i = parseFloat(strDataValue[3]);
    if (i <= 0 || i > 31) { /**/
      infoValidation = false;
    }
  } else {
    infoValidation = false;
  }
  if (!infoValidation) {
    alert("請輸入 YYYY/MM/DD 日期格式");
  }
  return infoValidation;
}

Html

<form method="post" name="dateCheckFrom"
      onsubmit="return dateValidationCheck(this.date.value);">
請依格式輸入日期 YYYY/MM/DD:
<input type="text" name="date" size="15" />
<input type="submit" value="送出資料" />
</form>


功能 : 判斷 v 是否是整數

function IsInt(v) {
  var vArr = v.match(/^[0-9]+$/);
  if (vArr == null) {
    return false;
  } else {
    return true;
  }
}

Modification in