如何强制验证来自 jquery 的 HTML 5 输入的数据?

How to force validate data of the HTML 5 input from jquery?

我确实有一个带有模式和标题的输入,以在数据错误的情况下显示错误,我不需要使用 post 方法,所以我只是做了一些 Jquery使用输入验证的代码,但我找不到如何显示输入的默认消息

这是 HTML5 输入:

<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>

这是 jquery 代码:

    $("#inputEnviar").click(
    function(){

        var userValidation = $("#user")[0].checkValidity();

        //validate if the pattern match
        if ( userValidation ){

            //code to do whatever I have to do if the data is valid

        } else {
            //if the data is invalid
            //the input already has a default message to show
            //then, how do I force to show
            $("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
        }

    });

这应该有效。 reportValidity() 函数将在您使用 setCustomValidity 设置后显示默认消息。

function send() {
    var input = $("#user")[0];
    input.setCustomValidity("");
    if(!input.checkValidity()) {
        input.setCustomValidity("watch me break");
        input.reportValidity();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>

如果验证失败,在您的 else 代码块中,设置要通知用户的自定义消息:

$("#user")[0].setCustomValidity("Please enter at least 5 characters.");

那么,你可以使用reportValidity() to show that message. From MDN:

The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

$("#inputEnviar").click(
  function() {
    var userValidation = $("#user")[0].checkValidity();
    //validate if the pattern match
    if (userValidation) {
      //code to do whatever I have to do if the data is valid
    } else {
      $("#user")[0].setCustomValidity("Please enter at least 5 characters.");
      var isValid = $('#user')[0].reportValidity();
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>

<input id="inputEnviar" type="button" value="Send">

对于旧浏览器(即 IE),您需要使用 polyfill。
周围有几个实现(像这样 git). This article 更深入地讨论了这个话题。