jQuery联系表单与PHP回退

时间:2013-01-26 08:24:01

标签: php validation mootools contact-form

我已经按照本教程学习如何使用PHP和jQuery创建联系表单。 据我所知,这个想法是让jquery工作,将php作为“备份”。

我没有遇到任何问题。或者我认为...... 但最终似乎jQuery无法正常工作。验证时我总是会“闪烁”(页面刷新)。

这是我试图在其中使用的页面: http://dccf.site88.net/test/dccf.php

这是PHP:     

// Set email variables
$email_to = 'luis_bento@hotmail.com';
$email_subject = 'Message from DCCF site';

// Set required fields
$required_fields = array('fullname','email','comment');

// set error messages
$error_messages = array(
    'fullname' => 'Please enter a Name to proceed.',
    'email' => 'Please enter a valid Email.',
    'comment' => 'Please enter a Message to continue.'
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// check form submittal
if(!empty($_POST)) {
    // Sanitise POST array
    foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));

    // Loop into required fields and make sure they match our needs
    foreach($required_fields as $field) {       

        // the field has been submitted?
        if(!array_key_exists($field, $_POST)) array_push($validation, $field);

        // check there is information in the field?
        if($_POST[$field] == '') array_push($validation, $field);

        // validate the email address supplied
        if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
    }

    // basic validation result
    if(count($validation) == 0) {

        // Prepare our content string
        $email_content = 'New Website Comment: ' . "\n\n";

        // simple email content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
        }

        // if validation passed ok then send the email
        mail($email_to, $email_subject, $email_content);

        // Update form switch
        $form_complete = TRUE;
    }
}
function validate_email_address($email = FALSE) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>




        <div id="formWrap">
    <h2>If you like our project, have any questions, or would like more information, please send us a message.</h2><!-- end of "Form Message" h2 -->
    <div id="form">
    <?php if($form_complete === FALSE): ?>
    <form action="dccf.php" method="post" id="comments_form">
        <div  class="row">
            <div class="label">Your Name:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. John Smith or Jane Doe</div><!-- end of .context --> 
        </div><!-- end of .row -->

        <div  class="row">
            <div class="label">Your Email:</div><!-- end of .label -->
            <div class="input">
                <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
            <div class="context">e.g. youremail@somewhere.com</div><!-- end of .context --> 
        </div><!-- end of .row -->

        <div  class="row">
            <div class="label">Your Message:</div><!-- end of .label -->
            <div class="input">
                <textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
            </div><!-- end of .input -->
        </div><!-- end of .row -->

        <div class="submit">
            <input type="submit" id="submit" name="submit" value"Send Message" />
        </div><!-- end of .submit -->

        </form>
        <?php else: ?>
        <p class="thanks">Thank you for your Message! We will get back to you as soon as possible.</p>
        <?php endif; ?>
    </div><!-- end of #form -->
</div><!-- end of #formWrap -->

和java脚本: 在:

    <script type="text/javascript">
    var nameError = '<?php echo $error_messages['fullname']; ?>';
    var emailError = '<?php echo $error_messages['email']; ?>';
    var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
验证中的

    window.addEvent('domready', function() {
// Get the form
var form = $('comments_form');

//  if the form is found...
if (form) {
    // obtain error fields
    var name = $('fullname');
    var email = $('email');
    var comment = $('comment');

    // Set the default status
    var isValid = true;

    // input error function for the error messages
    var addError = function (field, msg) {
        field.addClass('error'); // Add error class to field
        var error = field.getParent().getElement('span') || new Element('span', {'class': 'error'}); // add error message if not already placed
        error.set('text', msg); // error text msg
        error.inject(field, 'after'); // Insert error message after field
    };

    // detach error function used to delete any error messages and remove the error class
    var removeError = function (field) {
        field.removeClass('error'); // Remove error class from form fields
        var error = field.getParent().getElement('span'); // find any existing error messages

        // destroy if error message
        if (error) {
            error.destroy();
        }
    };

    //  insert submit form event
    form.addEvent('submit', function (e) {
        // Test name length
        if (name.get('value').length === 0) {
            isValid = false;
            addError(name, nameError);
        } else {
            isValid = true;
            removeError(name);
        }

        // check email length
        if (email.get('value').length === 0) {
            isValid = false;
            addError(email, emailError);
        // check email validity
        } else if (!email.get('value').test(/^([a-zA-Z0-9\+_\-]+)(\.[a-zA-Z0-9\+_\-]+)*@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/)) {
            isValid = false;
            addError(email, emailError);
        } else {
            isValid = true;
            removeError(email);
        }

        // check comment length
        if (comment.get('value').length === 0) {
            isValid = false;
            addError(comment, commentError);
        } else {
            isValid = true;                     
            removeError(comment);
        }

        // If form invalid then stop event happening
        if (!isValid) {
            e.stop();
        }
    });
}   
});

感谢您的帮助! =)

编辑: 控制台上出现了几个错误(加载页面时,而不是提交表单的人):

  • 无法识别和忽略视口参数键“width_device-width”。 dccf.php:8
  • TypeError:'undefined'不是函数(评估'form.addEvent')validation.js:4

1 个答案:

答案 0 :(得分:0)

我已删除了之前的答案,因为您的代码存在很多问题。

这是jQuery等效的,删除了所有错误,所以它

  1. 如果只填写其中一个字段
  2. ,则不再允许提交
  3. 不使用string.test(正则表达式),而是使用正确的regex.test(字符串)
  4. 使用全名而不是名称字段的名称
  5. 每次按下提交时重置isValid
  6. DEMO

    $(function() {
      // Get the form
      var form = $('#comments_form');
    
      //  if the form is found...
      if (form) {
    
        // input error function for the error messages
        var addError = function (field, msg) {
            field.addClass('error'); // Add error class to field
            var error = field.parent().find('span') || $('<span>', {'class': 'error'}); // add error message if not already placed
            error.html(msg); // error text msg
            field.after(error); // Insert error message after field
        };
    
        // detach error function used to delete any error messages and remove the error class
        var removeError = function (field) {
            field.removeClass('error'); // Remove error class from form fields
            var error = field.parent().find('span'); // find any existing error messages
    
            // destroy if error message
            if (error) {
                error.remove();
            }
        };
    
        //  insert submit form event
        form.on('submit', function (e) {
    
    
            // Set the default status
            var isValid = true;
    
            // Test name length
            var name = $("#fullname");
            if (name.val().length === 0) {
                isValid = false;
                addError(name, nameError);
            } else {
                removeError(name);
            }
    
            // check email length
            var email = $("#email");
            var emailVal = email.val();
            if (emailVal.length === 0) {
                isValid = false;
                addError(email, emailError);
            // check email validity
            } else if (!/^([a-zA-Z0-9\+_\-]+)(\.[a-zA-Z0-9\+_\-]+)*@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/.test(emailVal)) {
                isValid = false;
                addError(email, emailError);
            } else {
                removeError(email);
            }
    
            // check comment length
            var comment = $("#comment");
            console.log(comment.val())
            if (comment.val().length === 0) {
                isValid = false;
                addError(comment, commentError);
            } else {
                removeError(comment);
            }
    
            // If form invalid then stop event happening
            if (!isValid) {
                e.preventDefault();
            }
        });
      }   
    });