HTML5验证

16

我想知道HTML5是否有双重输入(写入两个相同的密码)的表单验证功能,而且您能否自己编写异常情况呢?

提前致谢!


虽然你可以这样做,但最好避免这样。通过 Ajax 在服务器端执行验证。 - Yang
6个回答

24

如果你想要更好一点且使用了HTML5的工具,请尝试这个链接: http://www.html5rocks.com/en/tutorials/forms/html5forms/

<label>Password:</label>
<input type="password" id="password" name="password">
<label>Confirm Password:</label>
<input type="password" id="passwordconf" name="passwordconf" oninput="check(this)">
<script language='javascript' type='text/javascript'>
function check(input) {
    if (input.value != document.getElementById('password').value) {
        input.setCustomValidity('The two passwords must match.');
    } else {
        // input is valid -- reset the error message
        input.setCustomValidity('');
   }
}
</script>

通过将以下内容添加到您的CSS中,可以使其更加华丽。 当输入字段未通过HTML5验证时,它会在错误的输入字段周围添加红色边框。

:invalid {
     border: 2px solid #ff0000;
}

完成了。您仍应使用alert()或服务器端验证来确保用户正确输入两个密码。不要依赖客户端任何内容。


2

我曾经遇到过类似的问题,为了使用HTML5 API解决它,我做了以下操作:设置了一个密码模式,要求密码至少包含八个字母和一个数字。然后为了让它们匹配,我做了:

    var password = document.querySelector('#password'),
        passwordConfirm = document.querySelector('#password_confirm');

    [].forEach.call([password, passwordConfirm], function(el) {
        el.addEventListener('input', function() {
            if (!el.validity.patternMismatch) {
                if ( password.value === passwordConfirm.value ) {
                    try{password.setCustomValidity('')}catch(e){}
                } else {
                    password.setCustomValidity("Password and password confirm doesn\'t match")
                }
            }
        }, false)
    });

使用el.validity.patternMismatch先检查模式的有效性,然后再检查两个的有效性。这是我的密码输入框,带有模式。

<input type="password" pattern="^((?=.*(\d|\W))(?=.*[a-zA-Z]).{8,})$" id="password" />


1

我很确定那是不可能的。此外,它可以很容易地被JavaScript覆盖,为什么不使用它呢?

这个完美地运作:

<script language="javascript"> 
function checkPassword() { 
    if (document.pwForm.pw1.value != document.pwForm.pw2.value) { 
        alert ('The passwords do not match!');
        return false; 
    } 
} 
</script>
<form action="filename.ext" name="pwForm" method="GET/POST">
    <input type="password" name="pw1" value=""><br />
    <input type="password" name="pw2" value=""><br />
    <input type="Submit" name="CheckPassword" value="Check Passwords" onClick="return checkPassword();">
</form>

虽然答案是正确的,但这段代码存在很多问题:1. 如果field1没有被更改,则不会添加自定义错误。2. 如果有人在pw1中输错了密码而在pw2中没有输错,并在字段保持无效后更改了此密码,则仍然无效。3. 只有在字段尚未具有自定义错误或自定义错误是由同一脚本添加的情况下(需要测试validity.customError/validationMessage),才应该更改自定义有效性。 - alexander farkas

0

我想这就是你要找的。

<p>Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd1" onchange="
  this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');
  if(this.checkValidity()) form.pwd2.pattern = this.value;
"></p>
<p>Confirm Password: <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" name="pwd2" onchange="
  this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');
"></p>

这将对密码和重新输入密码字段进行验证。


0

另一个选择是使用http://jqueryvalidation.org/validate/,如果您不介意使用Jquery来完成您的工作。

查看http://jqueryvalidation.org/equalTo-method

<form id="myform">
  <label for="password">Password</label>
  <input id="password" name="password" />
  <br/>
  <label for="password_again">Again</label>
  <input class="left" id="password_again" name="password_again" />
  <br>
  <input type="submit" value="Validate!">
</form>

<script>
  $( "#myform" ).validate({
    rules: {
      password: "required",
      password_again: {
        equalTo: "#password"
      }
    }
  });
</script>

如果需要,您还可以编写更复杂的方法:http://jqueryvalidation.org/category/plugin/


0

谢谢Kicker,这真的很有用。

我稍微扩展了一下,使密码和确认密码输入在开始输入时立即无效。

var password = document.querySelector(' input[name=usr_password]');
var passwordConfirm = document.querySelector(' input[name=usr_password_confirm]');
if (password && passwordConfirm)
{
    [].forEach.call([password, passwordConfirm], function(el) {
        el.addEventListener('input', function() {
            if ( el.validity.patternMismatch === false) {
                if ( password.value === passwordConfirm.value ) {
                    try{
                        password.setCustomValidity('');
                        passwordConfirm.setCustomValidity('');

                    }
                    catch(e){}
                }
                else {
                    password.setCustomValidity("The two passwords do not match");
                }
            }
            if ((password.checkValidity() && passwordConfirm.checkValidity()) === false)
            {
                password.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
                passwordConfirm.setCustomValidity("The two passwords do not match, and they don't comply with the password rules.");
            }
            else
            {
                password.setCustomValidity('');
                passwordConfirm.setCustomValidity('');

            }
        }, false)
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接