带验证的日期掩码

date mask with validation

我曾经通过在字段中添加对模糊的调用来使用此解决方案,如果它返回 false,我会显示一个工具提示,说明日期无效

function date(ele){
var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
return dateRegex.test(ele.val());
}

问题是,在这个项目中,我需要使用没有工具提示的旧版本 bootstrap。

我正在考虑复制最新的 bootsrap 的 css 来创建我自己的工具提示,但在此之前我想看看是否有人知道解决此日期验证的更好方法。最好的解决方案是为输入制作一个掩码以及验证,并且已经显示类似工具提示或 html5 警告日期无效的消息。

我想知道是否有任何方法可以实现一个日期掩码,如果日期无效并且不允许提交,则向用户验证和 returns,就像我们在中使用 required 时一样场。是否有执行此操作的实现或库?

类似于invalide-feedback or valid-tooltip 日期

如果您要求定制一些东西,可以按照 MDN: Client-side form validation 中所示的方式进行。我很快就把它放在一起,并没有花时间让它看起来不错,但它使用约束验证 API 和你的 JS 函数工作,只是为了表明你可以混合和匹配。

// There are many ways to pick a DOM node
const form = document.getElementsByTagName('form')[0];

const date = document.getElementById('date');
const dateError = document.getElementById('dateError');
const dateGroup = document.querySelector('.form-group');

date.addEventListener('input', function(event) {
    // Each time the user types something, we check if the form fields are valid.
    if (date.validity.valid && dateValidator(date)) {
        dateGroup.classList.remove("has-error");

        // In case there is an error message visible, if the field is valid, we remove it
        dateError.innerHTML = '';
        dateError.className = 'error'; // Reset the visual state of the message

    } else {
        // If there is still an error, show the correct error
        showError();
    }
});

form.addEventListener('submit', function(event) {
    // if the date field is valid, we let the form submit
    if (!date.validity.valid) {
        // If it isn't, we display an appropriate error message
        showError();
        // Then we prevent the form from being sent by canceling the event
        event.preventDefault();
    }
});

function showError() {
    if (date.validity.valueMissing) {
        // If the field is empty display the following error message.
        dateError.textContent = `Value missing.`;
        dateGroup.classList.add("has-error");
    } else if (date.validity.typeMismatch) {
        // If the field doesn't contain a date isplay the following error message.
        dateError.textContent = `Type mismatch.`;
        dateGroup.classList.add("has-error");
    } else if (date.validity.tooShort) {
        // If the data is too short display the following error message.
        dateError.textContent = `Too short. `;
        dateGroup.classList.add("has-error");
    } else if (!dateValidator(date)) {
        dateError.textContent = `Wrong Format.`;
        dateGroup.classList.add("has-error");
    }

    // Set the styling appropriately
    dateError.className = 'error active';
};

function dateValidator(ele) {
    var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    return dateRegex.test(ele.value); //TODO: Update ele.val() if it's jquery or whatever
}

$("form").submit(function (e) {
   var valid = date.validity.valid && dateValidator(date);
   // do your validation here ...
   if (!valid) {
      e.preventDefault();
      return false;
   }
}); 
input[type=text]{
  -webkit-appearance: none;
  appearance: none;

  width: 140px;
  border: 1px solid #333;
  margin: 0;
  font-size: 90%;

  box-sizing: border-box;
}
/* This is the style of our error messages */
.error {
  width  : 100%;
  padding: 0;

  font-size: 80%;
  color: white;
  background-color: #900;
  border-radius: 0 0 5px 5px;

  box-sizing: border-box;
}
.error.active {
  padding: 0.3em;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>JavaScript form validation - checking date [mm/dd/yyyy or mm-dd-yyyy format]</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body onload='document.form.date.focus()'>
    <form name="form" action="#">
        <label for="mail">
            <p>Please enter a date:</p>
            <div class="form-group has-error has-feedback">
                <label class="col-sm-4 control-label" for="inputError">Date:</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" id="date" name="date" required minlength="10" placeholder="DD/MM/YYYY"> <span class="error" id="dateError" aria-live="polite"></span> </div>
            </div>
        </label>
        <br>
        <input type="submit" name="submit" value="Submit" /> </form>
</body>
</html>

如果这还不够好,您可以查看自定义 Bootstrap 插件,例如 FormValidation(适用于 v3/4)