使用setCustomValidity填充的 Bootstrap 4无效

vawmfj5a  于 2022-12-08  发布在  Bootstrap
关注(0)|答案(1)|浏览(170)

在 Bootstrap 文档中,它指出:
您可以使用JavaScript中的setCustomValidity提供自定义有效性消息。
我认为这意味着当调用验证时,validity消息将填充.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>

我希望触发验证,并让消息填充.“invalid-feedback”,但事实并非如此。
我错过了什么吗?

fxnxkyjh

fxnxkyjh1#

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

  • 通过点击按钮提交表单,输入将被验证。如果输入无效,setCustomValidity中指定的消息

函数将出现,如果它是肯定的,该表单将被发送
在脚本执行过程中,代码中的许多问题都是由于无法读取为获取forminput而创建的变量。
此外,您的脚本不包含在验证为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>

相关问题