Bootstrap 4 使用 setCustomValidity 填充 .is-invalid

Mat*_*man 7 jquery twitter-bootstrap bootstrap-4

在引导程序文档中,它指出:

您可以在 JavaScript 中使用 setCustomValidity 提供自定义有效性消息。

我读到这意味着有效性消息将在调用验证时填充 .is-invalid 元素。

我的例子如下:

<script type="text/javascript">
    const myForm = $("#my-form").get()[0];
    const myInput = $("#my-input").get()[0];
    myInput.setCustomValidity("Error");
    myForm.checkValidity();
</script>
<form id="myform" novalidate>
    <div class="form-group">
        <label for="myInput" class="control-label">Input:</label>
        <input class="form-control" id="myInput">
        <span class="invalid-feedback"></span>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

我希望触发验证并让消息填充“.invalid-feedback”,但事实并非如此。

我错过了什么吗?

小智 0

我不知道我是否很好地理解你想要什么,但我按照以下逻辑做了:

  • 通过单击按钮提交表单,输入将得到验证。如果无效,setCustomValidity
    则会出现函数中指定的消息,如果是肯定的,则会发送表格

脚本执行期间代码中的许多问题是由于它无法读取为获取 和 而创建的form变量input

此外,您的脚本不包含在验证失败时停止事件的方法false

 <form id="myform" class="needs-validation" novalidate>
   <div class="form-group">
     <label for="myInput" class="control-label">Input:</label>
     <!-- The old input did not have its type definition and was not defined as required -->
     <!--<input class="form-control" id="myInput">-->
     <input type="text" class="form-control" id="myInput" required>
     <span id="msg" class="invalid-feedback"></span>
   </div>
   <div class="col-12">
     <button id="btnSubmit" class="btn btn-primary" type="submit">Submit form</button>
   </div>
 </form>

 <script>
  //Setting the custom validity message to "Error" and then displaying the message.
   $(function() {
     //Setting up an event handler for the click event on the button.
     $("#btnSubmit").on("click", function(e) {
       //Getting the first element of the jQuery object.
       var form = $("#myform").get()[0];
       //Checking the validity of the form.
       var isValid = form.checkValidity();
       //Getting the first element of the jQuery object.
       var input = $("#myInput")[0];
       //Preventing the form from being submitted.
       if (!isValid) {
         e.preventDefault();
         e.stopPropagation();
       }
       //Adding the class `was-validated` to the form.
       form.classList.add('was-validated');
       //Setting the custom validity message to "Error" and then displaying the message.
       input.setCustomValidity('Error');
       //Setting the innerHTML of the element with the id of msg to the validationMessage of the input element.
       document.getElementById('msg').innerHTML = input.validationMessage;

       return false; // For testing only to stay on this page
     });
   });

 </script>
Run Code Online (Sandbox Code Playgroud)