首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带验证的日期掩码

带验证的日期掩码
EN

Stack Overflow用户
提问于 2020-11-24 23:08:38
回答 1查看 519关注 0票数 1

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

代码语言:javascript
运行
复制
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(?: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消息的内容,警告日期无效。

我想知道是否有任何方法可以实现日期掩码,如果日期无效并不允许提交,就可以验证并返回给用户,就像我们在字段中使用required一样。有没有这样做的实现或库?

类似于日期的invalide-feedbackvalid-tooltip

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-25 08:05:42

如果你想要一些定制的东西,可以像MDN: Client-side form validation上显示的那样完成。我很快地把它们组合在一起,并没有花费时间让它看起来更漂亮,但它使用约束验证API和JS函数来工作,只是为了展示您可以混合和匹配。

代码语言:javascript
运行
复制
// 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(?: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;
   }
}); 
代码语言:javascript
运行
复制
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;
}
代码语言:javascript
运行
复制
<!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>

如果这还不够好,你可以看看定制的引导插件,比如FormValidation (可用于v3/4)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64989275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档