如何编写脚本实现联系人姓名输入的正则校验(非空+仅字符空格)
You don’t need a new function—you can integrate the regex validation directly into your existing validate() function! Let’s fix and expand your code step by step:
First, a quick correction: your current check if (contact_name == "") is comparing the DOM element itself to an empty string, not the actual input value. You need to use .value to access what the user typed.
Here’s the updated validate() function with the regex validation included:
function validate() { var contactInput = document.getElementById('contact'); var contactName = contactInput.value.trim(); // Trim whitespace to catch inputs with only spaces // Check if input is empty if (contactName === "") { alert("Contact name must be filled out"); contactInput.focus(); // Guide user back to the input field return false; } // Regex for letters (including Unicode/accented characters) and spaces var nameRegex = /^\p{L}+(?: \p{L}+)*$/u; // The 'u' flag enables Unicode support // Check if input matches the regex rules if (!nameRegex.test(contactName)) { alert("Contact name can only contain letters and spaces"); contactInput.focus(); return false; } // All checks passed return true; }
Key Details to Note:
- The
uflag in the regex is critical—it enables support for Unicode characters (likeé,ñ,ü), which your chosen regex^\p{L}+(?: \p{L}+)*$depends on to work correctly across different languages and name formats. - Using
.trim()ensures we catch cases where the user only enters spaces (which would otherwise pass the empty check but fail the regex). - Adding
.focus()improves usability by directing the user back to the input field when validation fails.
How to Connect It to Your Form:
Make sure your form triggers the validation when submitted by adding the onsubmit event:
<form onsubmit="return validate()"> <p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p> <button type="submit">Submit</button> </form>
This setup will run the validate() function whenever the user tries to submit the form. If any check fails, it returns false to block submission and shows an alert to the user.
Content of the question originates from Stack Exchange, asked by T.Gowing

