如何处理多标签HTML表单上的验证,我如何知道存在验证错误

时间:2018-07-27 07:29:52

标签: html5

我正在使用可用于HTML5中输入字段的内置验证

例如,在这里我限制了可以输入的数字范围

<input name="1_DISC_NO" id="1_DISC_NO" value="-1" style="width:100%" type="number" min="1" max="999">

因此,如果用户输入无效值,他们会收到一条不错的消息

enter image description here

问题在于此页面具有多个选项卡,因此如果他们转到另一个选项卡进行一些更改并单击 Save ,将不会发生任何事情,因为我们在另一个选项卡上仍然有错误,但是什么也没有表示有错误

enter image description here

我是否可以通过一种简单的方法来知道存在验证错误,因此我可以在页面顶部显示错误消息。

3 个答案:

答案 0 :(得分:3)

您可以做的是使用oninvalid HTML属性。当输入的输入无效时,此属性可用于触发自定义脚本。创建一个错误部分,并在触发invalidFunction时向其填充消息,如果能够提交表单,则将其清除。查看下面的代码段

<!DOCTYPE html>
<html>
<body>

<h2 id="errorHeader"></h2>

<form action="/action_page.php">
  First name: <input type="text" name="fname" required oninvalid="invalidFunction(event, 'First Name is mandatory')"><br>
  <button type="submit">
  Submit
  </button>
</form>

<script>
function invalidFunction(e, message) {
e.preventDefault();
document.getElementById('errorHeader').innerText = message;
}
</script>
</body>
</html>

答案 1 :(得分:0)

这是我如何使用jQuery依赖脚本来完成此操作的方法。 不要忘记所有这些都必须在form标签中

<form>
    <ul class="errorMessages"></ul>

    <div>
        <label for="name">Name:</label>
        <input id="name" type="text" required>
    </div>

    <div>
        <label for="comments">Comments:</label>
        <textarea id="comments" required></textarea>
    </div>

    <div class="buttons">
        <button>Submit</button>
    </div>
</form>​

<script>
    var createAllErrors = function() {
        var form = $( this ),
            errorList = $( "ul.errorMessages", form );

        var showAllErrorMessages = function() {
            errorList.empty();

            // Find all invalid fields within the form.
            var invalidFields = form.find( ":invalid" ).each( function( index, node ) {

                // Find the field's corresponding label
                var label = $( "label[for=" + node.id + "] "),
                    // Opera incorrectly does not fill the validationMessage property.
                    message = node.validationMessage || 'Invalid value.';

                errorList
                    .show()
                    .append( "<li><span>" + label.html() + "</span> " + message + "</li>" );
            });
        };

        // Support Safari
        form.on( "submit", function( event ) {
            if ( this.checkValidity && !this.checkValidity() ) {
                $( this ).find( ":invalid" ).first().focus();
                event.preventDefault();
            }
        });

        $( "input[type=submit], button:not([type=button])", form )
            .on( "click", showAllErrorMessages);

        $( "input", form ).on( "keypress", function( event ) {
            var type = $( this ).attr( "type" );
            if ( /date|email|month|number|search|tel|text|time|url|week/.test ( type )
              && event.keyCode == 13 ) {
                showAllErrorMessages();
            }
        });
    };

    $( "form" ).each( createAllErrors );
</script>

我希望对您有帮助

答案 2 :(得分:0)

请参考以下代码段:

<!-- <!DOCTYPE html> -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tab Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
    .tab {
        overflow: hidden;
        border: 1px solid #ccc;
        background-color: #f1f1f1;
    }

    .tab button {
        background-color: inherit;
        float: left;
        border: none;
        outline: none;
        cursor: pointer;
        padding: 14px 16px;
        transition: 0.3s;
    }

    .tab button:hover {
        background-color: #ddd;
    }

    .tab button.active {
        background-color: #ccc;
    }

    .tabcontent {
        display: none;
        padding: 6px 12px;
        border: 1px solid #ccc;
        border-top: none;
    }
</style>
<script>
    $(document).ready(function () {
        $('#ErrorList').html('');
        $('#Notifications').css('display', 'none');
        $('#CloseNotification').click(function () {
            $('#Notifications').fadeOut();
        });
    });

    function setErrors(errors) {
        var errorList = '';
        for (i = 0; i < errors.length; i++) {
            errorList += '<li>' + errors[i] + '</li>'
        }
        if (errorList) {
            $('#Notifications').fadeIn();
            $('#ErrorList').html(errorList);
        }
    }

    function ValidateData() {
        var Errors = [];
        if ($('#firstName').val() == '')
            Errors.push('First Name is required.');
        if ($('#primaryEmail').val() == '')
            Errors.push('Primary Email is required.');
        setErrors(Errors);
    }

    function openTab(evt, tabName) {
        var i, tabcontent, tablinks;
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.className += " active";
    }
</script>
</head>
<body>
<div id="Notifications" class="alert alert-danger">
    <a id="CloseNotification" href="#" class="close">&times;</a>
    <div id="ErrorList">
    </div>
</div>
<div class="tab">
    <button class="tablinks" onclick="openTab(event, 'Basic Information')">Basic Information</button>
    <button class="tablinks" onclick="openTab(event, 'Professional Information')">Professional Information</button>
</div>
<div id="Basic Information" class="tabcontent active" style="display:block;">
    <div class="form-group">
        <label>First Name</label>
        <input type="text" class="form-control" id="firstName">
    </div>
    <div class="form-group">
        <label>Last Name</label>
        <input type="text" class="form-control" id="lastName">
    </div>
    <div class="form-group">
        <label>Address</label>
        <input type="text" class="form-control" id="address">
    </div>
</div>
<div id="Professional Information" class="tabcontent">
    <div class="form-group">
        <label>Primary Email Address</label>
        <input type="email" class="form-control" id="primaryEmail">
    </div>
    <div class="form-group">
        <label>Alternate Email Address</label>
        <input type="email" class="form-control" id="alternateEmail">
    </div>
</div>
<br /><br />
<button class="btn btn-primary" onClick="ValidateData()">Validate and Save</button>
</body>
</html>

在ValidateData()中,可以放置自定义验证,并使用setErrors()可以设置错误。