使用jQuery实现OnInput事件表单校验遇阻,请求协助
Hey Martin, let's troubleshoot why your first name field validation isn't working properly. I've looked over your code and there are a couple of common issues that might be causing this, plus some small tweaks to make it more robust.
Most Likely Culprit: DOM Not Ready Before Script Runs
The biggest reason your input event handler isn't firing is probably that your jQuery code is running before the DOM has fully loaded. If your script is placed in the <head> section of your HTML, the #fName element doesn't exist yet when jQuery tries to bind the event, so nothing gets attached.
Fix This First: Wrap Code in $(document).ready()
Wrap your validation code inside a $(document).ready() block to ensure it only runs once all elements are available:
$(document).ready(function() { $('#fName').on("input", function(e) { // Use $(this) to reference the input element directly (cleaner than re-selecting) var value = $(this).val().trim(); // Trim whitespace to handle accidental spaces var fReg = /^[a-zA-Z'` ]+$/i; // Check if the value matches the regex OR is empty (since the field is required, but real-time validation might not need to yell at empty input yet) if (fReg.test(value) || value === "") { $("#firstNameErr").hide(); } else { $("#firstNameErr").show(); } }); });
Other Small Improvements & Checks
- Use
$(this)instead of re-selecting#fName: This is more efficient and cleaner—since you're already inside the input's event handler,$(this)refers directly to the#fNameelement. - Trim input value: Adding
.trim()ensures that accidental leading/trailing spaces don't trigger false errors (unless you want to allow only spaces, but that's usually not intended for a first name field). - Handle empty input: The original regex will fail on an empty string (since
+requires at least one character). If you don't want to show the error when the field is empty (since it has therequiredattribute anyway), add a check forvalue === ""to hide the error. - Simplify selectors:
$("#firstNameErr")works just as well as$("label#firstNameErr")—IDs are unique, so you don't need to specify the tag name.
Verify Your Setup
Double-check these things too:
- Make sure you've included the jQuery library before your custom script. For example:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Your validation script comes next --> - Ensure your script is placed either inside the
$(document).ready()block or at the very bottom of your HTML (right before the closing</body>tag)—this ensures all elements are loaded before the script runs.
Once you make these changes, your real-time validation should start working as expected: the error label will show up immediately when invalid characters are entered, and hide when the input matches the regex or is empty.
内容的提问来源于stack exchange,提问作者Martin

