首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有fallback的jQuery联系人表单

带有fallback的jQuery联系人表单
EN

Stack Overflow用户
提问于 2013-01-26 08:24:00
回答 1查看 653关注 0票数 0

本教程介绍了如何使用PHP和jQuery制作联系人表单。我所理解的想法是让jquery和php作为“备份”工作。

我遵守了教程,没有任何问题。或者我是这么想的。但最终看来,jQuery似乎不起作用。验证时,我总是得到“眨眼”(页面刷新)。

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

下面是PHP:

代码语言:javascript
复制
// 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脚本:在:

代码语言:javascript
复制
    <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>

在validation.js中:

代码语言:javascript
复制
    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();
        }
    });
}   
});

谢谢你的帮助!

编辑:在控制台上获得了几个错误(在加载页面时,没有一个提交表单):

  • 视口参数键“宽度_设备-宽度”未被识别和忽略。dccf.php:8
  • TypeError:“未定义”不是一个函数(计算'form.addEvent') validation.js:4
EN

回答 1

Stack Overflow用户

发布于 2013-01-26 10:09:09

我已经删除了我以前的答案,因为你的代码有很多问题。

下面是删除所有错误的jQuery等价物,因此

  1. 如果只填写了后面的一个字段,则不再允许提交。
  2. 不是使用string.test(regex),而是使用正确的regex.test(字符串)
  3. 在name字段中使用全名而不是名称。
  4. 每次按下提交时重置isValid

演示

代码语言:javascript
复制
$(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();
        }
    });
  }   
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14535174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档