JS表单submit事件绑定失效及姓名正则优化问题求助
Hey there! Let's work through your two form development issues step by step:
Issue 1: Submit Event Not Triggering
The problem here is that you're trying to attach a submit event listener to the submit button itself—but the submit event belongs to the <form> element, not the button. When a user submits the form (either by clicking the button or pressing Enter), the event fires on the form, not the button.
Here's the fixed JavaScript code:
(function() { "use strict"; // Target the form element instead of the submit button document.getElementById('escribenos').addEventListener('submit', enviar); function enviar(event) { event.preventDefault(); // Prevents the default form submission page reload console.log("you submitted the form"); } })();
This way, when the form is submitted, your function will fire as expected and log the message to the console.
Issue 2: Regex for Names with Middle Names
Your current regex [A-Za-z]+\s+[A-Za-z]+ only matches exactly two name parts. To support at least two parts (including middle names), we need to allow one or more additional "space + name" segments after the first name.
Use this updated regex pattern:
[A-Za-z]+(?:\s+[A-Za-z]+)+
Breakdown:
[A-Za-z]+: Matches the first name (one or more letters)(?:\s+[A-Za-z]+)+: A non-capturing group (?:...) that matches a space followed by another name part. The+at the end means this group can repeat one or more times—ensuring there's at least one additional name part (so total of 2+ names).
Here's the updated HTML input line:
<input type="text" name="name" id="name" pattern="[A-Za-z]+(?:\s+[A-Za-z]+)+" required value=""/>
If you want the regex to be case-insensitive (so it accepts lowercase and uppercase letters without strict matching), you can add the (?i) flag at the start:
(?i)[A-Za-z]+(?:\s+[A-Za-z]+)+
内容的提问来源于stack exchange,提问作者roger rengifo

