在文本框 ontype 中以 YYYY-MM-DD HH:MM 格式验证日期

Validating Date in YYYY-MM-DD HH:MM format inside textbox ontype

我想验证一个文本框,它需要接受一个格式 YYYY-MM-DD 格式的日期 HH:MM 使用

<!DOCTYPE html>
<html>
<body>

<form action="/action_page_post.php" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>

如果不是上述格式,它应该变成红色或发光。

只是屏蔽它怎么样?

JSfiddle

Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);

function applyDataMask(field) {
    var mask = field.dataset.mask.split('');
    
    // For now, this just strips everything that's not a number
    function stripMask(maskedData) {
        function isDigit(char) {
            return /\d/.test(char);
        }
        return maskedData.split('').filter(isDigit);
    }
    
    // Replace `_` characters with characters from `data`
    function applyMask(data) {
        return mask.map(function(char) {
            if (char != '_') return char;
            if (data.length == 0) return char;
            return data.shift();
        }).join('')
    }
    
    function reapplyMask(data) {
        return applyMask(stripMask(data));
    }
    
    function changed() {   
        var oldStart = field.selectionStart;
        var oldEnd = field.selectionEnd;
        
        field.value = reapplyMask(field.value);
        
        field.selectionStart = oldStart;
        field.selectionEnd = oldEnd;
    }
    
    field.addEventListener('click', changed)
    field.addEventListener('keyup', changed)
}
ISO Date: <input type="text" value="" data-mask="____-__-__  __:__"/>

Source

这将测试

  • 模式
  • 有效日期

function isValid(str) {
  var isPattern = /^20[1-9][0-9]-[0-1][0-2]-[0-3][0-9] [0-2][0-4]:[0-5][0-9]$/.test(str);
  if (!isPattern) return false;
  var d = new Date(str);
  return (!isNaN(d));
}
window.onload=function() {
  document.querySelector("input[name=date]").onkeyup=function() {
    var val = this.value;
    this.className = isValid(val)?"":"glow"
  }
}
.glow { background-color:pink }
<form>
<input type="text" name="date" required>
  <input type="submit" value="Submit">
</form>