Can you require two form fields to match with HTML5?

后端 未结 7 1578
你的背包
你的背包 2020-11-29 23:56

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 fiel

相关标签:
7条回答
  • 2020-11-30 01:01

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

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

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

    0 讨论(0)
提交回复
热议问题