Html HTML5 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9446057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:47:01  来源:igfitidea点击:

HTML5 validation

formshtmlvalidation

提问by user1156691

I wonder if HTML5 have any formvalidation for dual entry (write 2 identical password) and can you write own exceptions?

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

Thanx in advance!

提前谢谢!

回答by Richard ?ak

If you want something a bit nicer and HTML5-utilising, try this: http://www.html5rocks.com/en/tutorials/forms/html5forms/

如果你想要更好的和 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>

Make it fancy by adding this to your CSS (below). It puts a red border around the offending input fields when they fail HTML5 validation.

通过将它添加到您的 CSS(如下)来让它变得漂亮。当 HTML5 验证失败时,它会在有问题的输入字段周围放置一个红色边框。

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

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.

全部完成。您仍然应该使用 alert() 或服务器端验证来确保用户正确输入两个密码。不要依赖客户端的任何东西。

回答by Mimo

I had a similar problem, and to solve it using the HTML5 api I did this: setted a pattern for the password to contain at least eight letters and a number. Then to make them matching I did:

我遇到了类似的问题,为了使用 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)
    });

where with el.validity.patternMismatchcheck for the pattern validity first and then check for the validity of the two. Here is my password input with the pattern.

其中 with 首先el.validity.patternMismatch检查模式有效性,然后检查两者的有效性。这是我使用模式输入的密码。

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

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

回答by Anton

I'm quite sure that's not possible. Also, it can be easily covered by javascript so why not use that instead?

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

This works perfectly well:

这非常有效:

<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>

回答by pgee70

Thanks Kicker, that was really useful.

谢谢 Kicker,这真的很有用。

I extended it a little to make the password and password confirm inputs to be invalid as soon as typing in the input started.

我对其进行了一些扩展,以使密码和密码确认输入在输入开始时立即无效。

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)
    });
}

回答by AeJey

I think this is what you are looking for.

我想这就是你要找的。

<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>

This will do the password and retype password fields validation.

这将执行密码并重新输入密码字段验证。

回答by FuzzyJulz

Another option is to use http://jqueryvalidation.org/validate/, if you don't mind using Jquery to do your dirty work.

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

Check out http://jqueryvalidation.org/equalTo-method

查看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>

You can also write more complicated methods if required: http://jqueryvalidation.org/category/plugin/

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