Html 您可以要求两个表单字段与 HTML5 匹配吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9142527/
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:17:30  来源:igfitidea点击:

Can you require two form fields to match with HTML5?

formshtml

提问by user981178

Is there a way to require the entries in two form fields to match using HTML5? Or does this still have to be done with javascript? For example, if you have two password fields and want to make sure that a user has entered the same data in each field, are there some attributes, or other coding that can be done, to achieve this?

有没有办法要求两个表单字段中的条目使用 HTML5 进行匹配?或者这仍然需要用javascript来完成吗?例如,如果您有两个密码字段,并且想要确保用户在每个字段中输入了相同的数据,是否可以通过某些属性或其他编码来实现这一点?

回答by Faisal

Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:

不完全是 HTML5 验证,但一点 JavaScript 可以解决问题,请按照以下示例进行操作:

<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('password').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }
</script>
<br /><br />
<input type="submit" />

回答by Francisco Costa

You can with regular expressions Input Patterns(check browser compatibility)

您可以使用正则表达式输入模式(检查浏览器兼容性

<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>

<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>

回答by wvdz

A simple solution with minimal javascript is to use the html attribute pattern (supported by mostmodern browsers). This works by setting the pattern of the second field to the value of the first field.

一个使用最少 javascript 的简单解决方案是使用 html 属性模式(大多数现代浏览器都支持)。这是通过将第二个字段的模式设置为第一个字段的值来实现的。

Unfortunately, you also need to escape the regex, for which no standard function exists.

不幸的是,您还需要转义正则表达式,因为它不存在标准函数。

<form>
    <input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
    <input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\^$\|]/g, "\$&");
    }
</script>

回答by ptrdo

JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output>element and an oninputform handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):

将需要 JavaScript,但通过使用中间<output>元素和oninput表单处理程序来执行比较,可以将代码量保持在最低限度(模式和验证可以增强此解决方案,但为了简单起见未在此处显示):

<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
  <input type="password" name="p1" value="" required />
  <input type="password" name="p2" value="" required />
  <output name="result"></output>
</form>

回答by EfisioBova

Not only HTML5 but a bit of JavaScript
Click [here]https://codepen.io/diegoleme/pen/surIK

不仅是 HTML5,还有一些 JavaScript
点击 [这里] https://codepen.io/diegoleme/pen/surIK

HTML

HTML

    <form class="pure-form">
    <fieldset>
        <legend>Confirm password with HTML5</legend>

        <input type="password" placeholder="Password" id="password" required>
        <input type="password" placeholder="Confirm Password" id="confirm_password" required>

        <button type="submit" class="pure-button pure-button-primary">Confirm</button>
    </fieldset>
</form>

JAVASCRIPT

爪哇脚本

var password = document.getElementById("password")
  , confirm_password = document.getElementById("confirm_password");

function validatePassword(){
  if(password.value != confirm_password.value) {
    confirm_password.setCustomValidity("Passwords Don't Match");
  } else {
    confirm_password.setCustomValidity('');
  }
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

回答by Little Brain

The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'. This will only be visible if developer tools are open but it still doesn't seem like a good idea.

使用模式和正则表达式的答案将用户的密码作为纯文本写入输入属性pattern='mypassword'。这仅在开发人员工具打开时才可见,但它似乎仍然不是一个好主意。

Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.

使用模式检查匹配的另一个问题是您可能希望使用模式来检查密码的形式是否正确,例如混合字母和数字。

I also think these methods won't work well if the user switches between inputs.

我还认为如果用户在输入之间切换,这些方法将无法正常工作。

Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.

这是我的解决方案,它使用更多的 JavaScript,但在更新任一输入时执行简单的相等性检查,然后设置自定义 HTML 有效性。仍然可以测试两个输入的模式,例如电子邮件格式或密码复杂性。

For a real page you would change the input types to 'password'.

对于真实页面,您可以将输入类型更改为“密码”。

<form>
    <input type="text" id="password1" oninput="setPasswordConfirmValidity();">
    <input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
    function setPasswordConfirmValidity(str) {
        const password1 = document.getElementById('password1');
        const password2 = document.getElementById('password2');

        if (password1.value === password2.value) {
             password2.setCustomValidity('');
        } else {
            password2.setCustomValidity('Passwords must match');
        }
        console.log('password2 customError ', document.getElementById('password2').validity.customError);
        console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
    }
</script>

回答by AreaEuro

As has been mentioned in other answers, there is no pure HTML5 way to do this.

正如其他答案中提到的那样,没有纯粹的 HTML5 方法可以做到这一点。

If you are already using JQuery, then this should do what you need:

如果您已经在使用JQuery,那么这应该可以满足您的需求:

$(document).ready(function() {
  $('#ourForm').submit(function(e){
      var form = this;
      e.preventDefault();
      // Check Passwords are the same
      if( $('#pass1').val()==$('#pass2').val() ) {
          // Submit Form
          alert('Passwords Match, submitting form');
          form.submit();
      } else {
          // Complain bitterly
          alert('Password Mismatch');
          return false;
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ourForm">
    <input type="password" name="password" id="pass1" placeholder="Password" required>
    <input type="password" name="password" id="pass2" placeholder="Repeat Password" required>
    <input type="submit" value="Go">
</form>