HTML5验证

use*_*691 15 forms validation html5

我想知道HTML5是否有双重输入的表格验证(写2个相同的密码),你能编写自己的例外吗?

Thanx提前!

Ric*_*Żak 23

如果你想要更好的东西和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>
Run Code Online (Sandbox Code Playgroud)

通过将其添加到CSS(下面)来实现它.当HTML5验证失败时,它会在违规输入字段周围添加红色边框.

:invalid {
     border: 2px solid #ff0000;
}
Run Code Online (Sandbox Code Playgroud)

All done. You should still use an alert() or server-side validation to ensure that the user inputs both passwords correctly. Don't rely on client-side anything.


Ant*_*ton 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>
Run Code Online (Sandbox Code Playgroud)