You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 validateEmail function is nested inside the if(!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 pass theMail.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?

  1. 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.
  2. Function placement: The validateEmail function is now in the main click handler scope, so it's always available when needed.
  3. Parameter fix: We pass the trimmed email string (theMail.val().trim()) to the validation function, not the jQuery object.
  4. Simplified regex: The new regex checks for the basic structure of an email (something@something.something) which covers most valid use cases.
  5. 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.
  6. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:37:44