使用无效字段阻止表单提交

时间:2017-01-08 16:08:07

标签: javascript forms validation alert

我一直在尝试制作一个简单的HTML表单,其中包含电话号码,密码和已确认的密码。我尝试使用HTML5必需属性来确保在提交时填写所有字段,但是由于发现Safari不支持,我继续使用来自不同堆栈溢出主题的以下代码来验证表单: / p>

var form = document.getElementById('text'); // form has to have ID: <form id="formID">
    form.noValidate = true;
    form.addEventListener('submit', function (event) { // listen for form submitting
        if (!event.target.checkValidity()) {
            event.preventDefault(); // dismiss the default functionality
            if (document.getElementById('password_confirm').value != document.getElementById('password').value) {
                alert('Passwords must match');
                //document.getElementById("alert_pw_match").style.color = rgba(37, 33, 90, 0.64);
            } else {
                // input is valid -- reset the error message
                alert('All fields are required');
            }
        }
    }, false);

我遇到的问题是,我希望不再使用标准警告框,只是突出显示相关字段或显示一些表明表单无效的文本,但每当我添加除了警告表单提交时不会发生任何事情。

0 个答案:

没有答案
相关问题