如何在jQuery中验证邮箱格式并实现合法时提交表单至数据库
Fixing Email Validation for Your Comment Submission Form
Hey Julian, let's sort out that email validation problem you're facing. Looking at your code, there are a few key issues preventing the validation logic from working as expected—let's break them down and fix them step by step.
Key Issues in Your Original Code
- Incorrect function placement: Your
validateEmailfunction is nested inside theif(!theName.val())block. That means the function only exists if the user hasn't filled in their name, which is the opposite of what you need. - Wrong parameter passed: When you call
validateEmail(theMail), you're passing the jQuery object instead of the actual email string value. You need to passtheMail.val()instead. - Flawed validation order: Your non-empty checks are nested incorrectly—right now, you only check the name if the comment is empty, and only validate the email if the name is empty. This means none of these checks run when all fields are filled.
- Overly complex regex: Your email regex works, but it's unnecessarily complicated. A simpler, widely accepted regex will do the job just as well.
Corrected Code
Here's the fixed version of your code with all these issues addressed:
// 点击发布评论按钮 $('#bt-add-com').click(function(){ var theCom = $('.the-new-com'); var theName = $('#name-com'); var theMail = $('#mail-com'); // First, validate all required fields in order if (!theCom.val().trim()) { swal("Error", "You need to write a comment!", "error"); return; // Stop execution here } if (!theName.val().trim()) { swal("Error", "You need to write a name!", "error"); return; // Stop execution here } // Email validation function (moved outside nested blocks) function validateEmail(email) { // Simplified, standard email regex var emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailReg.test(email.trim()); } // Check email validity var emailValue = theMail.val().trim(); if (!emailValue || !validateEmail(emailValue)) { swal("Error", "Please enter a valid email address!", "error"); return; // Stop execution here } // If all validations pass, submit the form via AJAX $.ajax({ type: "POST", url: "comments/ajax/add-comment2.php", data: { act: 'add-com', id_post: <?php echo $id_post; ?>, name: theName.val().trim(), email: emailValue, comment: theCom.val().trim() }, success: function(html){ // Clear form fields theCom.val(''); theMail.val(''); theName.val(''); $('.new-com-bt').fadeIn(); $('.response').fadeIn().append(html); $('.new-com-cnt').hide('slow');// 隐藏表单 swal("Success", "Your comment is posted", "success"); } }); });
What Changed?
- Validation order: We now check each field one by one, stopping execution immediately if any field fails validation (using
return). This ensures all checks run in the right sequence. - Function placement: The
validateEmailfunction is now in the main click handler scope, so it's always available when needed. - Parameter fix: We pass the trimmed email string (
theMail.val().trim()) to the validation function, not the jQuery object. - Simplified regex: The new regex checks for the basic structure of an email (something@something.something) which covers most valid use cases.
- Data formatting: Instead of concatenating the data string, we use an object for the AJAX data—this is cleaner and avoids issues with special characters.
- Trimming whitespace: We add
.trim()to all input values to handle accidental leading/trailing spaces.
This code will now properly validate the email format, block submission if any field is invalid, and only send the AJAX request when all checks pass.
内容的提问来源于stack exchange,提问作者JulianJ
相关产品推荐
相关产品推荐

