\n\n\nThis code block employs the matchFields() function to ensure that field1 and field2 are 100% matching twins. Otherwise, it triggers the alert and blocks form submission.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Alex Kataev","url":"https://explain.codes//author/alex-kataev"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-02-01T13:00:01.227Z","dateModified":"2025-02-01T13:00:02.899Z"}
Explain Codes LogoExplain Codes Logo

Can you require two form fields to match with HTML?

javascript
real-time-validation
user-experience
client-side-validation
Alex KataevbyAlex Kataev·Feb 1, 2025
TLDR

To ensure two form fields match, we need a JavaScript validator. This script compares the input values on form submission and blocks the submission if they aren't equal. Here's the bare-bones implementation:

<form onsubmit="return matchFields()"> <input type="text" id="field1" required> <input type="text" id="field2" required> <button>Submit</button> </form> <script> function matchFields() { if (document.getElementById('field1').value === document.getElementById('field2').value) { return true; } else { alert('Fields must match... just like socks!'); return false; } } </script>

This code block employs the matchFields() function to ensure that field1 and field2 are 100% matching twins. Otherwise, it triggers the alert and blocks form submission.

User-friendly feedback with real-time validation

To enhance user experience, we use a little more JavaScript action to deliver real-time validation feedback with the help of the oninput event.

<input type="password" id="password" required pattern=".{8,}" title="8 characters minimum"> <input type="password" id="confirm_password" required oninput="validatePassword()"> <span id="message"></span> <script> function validatePassword() { if(document.getElementById('password').value === document.getElementById('confirm_password').value) { document.getElementById('message').innerText = '✅ Passwords match!'; document.getElementById('confirm_password').setCustomValidity(''); } else { document.getElementById('message').innerText = '❌ Passwords do not match!'; document.getElementById('confirm_password').setCustomValidity('Passwords must match, or else...'); } } </script>

Here we deploy setCustomValidity() to highlight a custom error message and give a gentle prod to the user when the passwords don't match. The pattern, title, and custom validity all synergize to create a more seamless user experience.

Server-side validation for robust data control

While client-side magic can enhance UX, server-side verification is your data's last line of defense, fighting off any shady business.

// Node.js with Express framework server-side pseudo-code app.post('/submit-form', (req, res) => { const { password, confirmPassword } = req.body; if (password !== confirmPassword) { res.status(400).send("Passwords must match... it's not rocket science!"); } else { // Proceed with password storage, safe and sound. } });

So always double-check your data on the server because a clever user can bypass client-side checks. As the saying goes, "Trust, but verify."

Compatibility checks and smart fallbacks

Not all browsers are created equal, and you need to check the compatibility of HTML5 features like the pattern attribute using caniuse.com. For the rogue browsers, deploy your JavaScript helpers:

if(!('pattern' in document.createElement('input'))) { // JavaScript to the rescue for legacy browser support! }

Compatibility checks like these ensure your application doesn't abandon any users in the wild unknown of older browsers.