Can you require two form fields to match with HTML5?

后端 未结 7 1634
你的背包
你的背包 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 00:42

    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.

    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.

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

提交回复
热议问题