Javascript 验证输入更改,仅在单击“提交”按钮时提交

标签 javascript ajax jquery-validate validation

我的网站上有一个表格。单击提交按钮时,将运行一个函数来获取每个字段的内容,根据 RegEx 和其他要求验证内容,然后如果一切正常,则通过 Ajax 将表单提交到 .php 邮件程序。

我希望表单在输入字段值更改时自动验证,或者当输入字段失去焦点时(我没有偏好,两者都很好),然后我希望表单仅在以下情况下提交用户单击表单上的“提交”按钮。如果用户在所有字段都有效之前单击“提交”按钮,我不希望提交表单。

这是我的代码:

    //contact form validation   
$(function(){
    $('.error').hide();
    // hide error messages onchange
    $("#contact-form").change(function(){
        $('.error').hide(); 
        $("label#name_error").hide(); 
        $("label#invalid_error").hide(); 
        $("label#email_error").hide(); 
        $("label#invalid_phone_error").hide(); 
        $("label#phone_error").hide(); 
        $("label#zip_error").hide();
    });

    // validate fields on click
    $(".cool-button").click(function(){
        $('.error').hide(); 
        $("label#name_error").hide(); 
        $("label#invalid_error").hide(); 
        $("label#email_error").hide(); 
        $("label#invalid_phone_error").hide(); 
        $("label#phone_error").hide(); 
        $("label#zip_error").hide(); 

        var name=$("input#contact_name").val();
        var email=$("input#contact_email").val();
        var emailRegEx =/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/
        var phone=$("input#contact_phone").val();
        var phone=phone.replace(/\s+-/g, "");
        var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/
        var zip=$("input#contact_zip").val();
        var best_time=$("input#contact_best_time").val();
        var message=$("textarea#contact_message").val();
        var timestamp=$("input#timestamp").val();

        if(name==""){
            $("label#name_error").show();
            $("input#contact_name").focus();return false;
            }
        if(email==""){
            $("label#email_error").show();
            $("input#contact_email").focus();return false;
            }
        if (document.getElementById('contact_email').value.search(emailRegEx )==-1) {
            $("label#invalid_error").show();
            $("input#contact_email").focus();return false;
            }
        if(phone==""){
            $("label#phone_error").show();
            $("input#contact_phone").focus();return false;
            }
        if (document.getElementById('contact_phone').value.search(phoneRegEx )==-1) {
            $("label#invalid_phone_error").show();
            $("input#contact_phone").focus();return false;
            }
        if(zip==""){
            $("label#zip_error").show();
            $("input#contact_zip").focus();return false;
            }
        if(message==""){
            $("label#message_error").show();
            $("textarea#contact_message").focus();return false;
            }
        else {
var dataString='contact_name='+name+'&contact_email='+email+'&contact_phone='+phone+'&contact_zip='+zip+'&contact_best_time='+best_time+'&timestamp='+timestamp+'&contact_message='+encodeURIComponent(message);
    $.ajax({
        type:"POST",
        url:"php/contact.php",
        data:dataString,
        success:function(){$('#contact-form').html("<div id='message'></div>");$('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at info@wirecrafters.com or call us at 800-924-9473</p>").hide().fadeIn(800,function(){$('#message').append("<img id='checkmark' src='images/submit2.png' />");});}});
        }
        return false;
    });

});

这里是表单的 HTML 和 PHP 代码

<form id="contact-form" method="post" action="#">
                          <p class="form-subscr-field">
                            <label for="contact_name" id="contact_name_label">Your name: *</label>
                            <input id="contact_name" type="text" name="contact_name" class="inputbox" size="10" required/>
                            <label class="error error-tip" for="contact_name" id="name_error" style="display: none; ">Please enter your name.</label>
                          </p>
                          <p class="form-subscr-field">
                            <label for="contact_email" id="contact_email_label">E-mail Address: *</label>
                            <input id="contact_email" type="email" name="contact_email" class="inputbox" size="10" required/>
                            <label class="error error-tip" for="contact_email" id="email_error" style="display: none; ">Please enter your email address.</label>
                            <label class="error error-tip" for="contact_email" id="invalid_error" style="display: none; ">Invalid email address.</label>
                          </p>
                          <fieldset class="w50">
                          <p class="form-subscr-field rowElem left">
                            <label for="contact_phone" id="contact_phone_label">Phone: *</label>
                            <input id="contact_phone" type="tel" name="contact_phone" class="inputbox"  size="10" required minlength="9"/>
                            <label class="error error-tip" for="contact_phone" id="phone_error" style="display: none; ">Please enter your phone number.</label>
                            <label class="error error-tip" for="contact_phone" id="invalid_phone_error" style="display: none; ">Please enter a valid phone number.</label>
                          </p>
                           </fieldset>
                           <fieldset class="w50">
                          <p class="form-subscr-field rowElem right">
                            <label for="contact_zip" id="contact_zip_label">Zip Code: *</label>
                            <input id="contact_zip" type="text" name="contact_zip" class="inputbox"  size="10" required minlength="5"/>
                            <label class="error error-tip" for="contact_zip" id="zip_error" style="display: none; ">Please enter your shipping zip code.</label>
                          </p>
                           </fieldset>
                          <p class="form-subscr-field">
                            <label for="contact_best_time" id="contact_best_time_label">Best time to Contact:</label>
                            <input id="contact_best_time" type="text" name="contact_best_time" class="inputbox"  size="10" />
                          </p>
                          <p class="form-subscr-field">
                            <label for="contact_message" id="comment_label">Your message: *</label>
                            <textarea id="contact_message" name="contact_message" rows="8" cols="30" required minlength="2"></textarea>
                            <label class="error error-tip" for="contact_message" id="message_error" style="display: none; ">This field is required.</label>
                          </p>
                          <input type="hidden" id="timestamp" name="timestamp" value="<?php
$hourdiff = "2"; // hours diff btwn server and local time
$insertdate = date("l, d F Y h:i a",time() + ($hourdiff * 3600));
print ("$insertdate");
?>" />
                          <div class="submit-contact">
                            <p>
                              <input type="submit" name="submit" class="cool-button csbutton-color spot-action" id="contact_button" value="Submit" />
                            </p>
                          </div>
                        </form>

最佳答案

这通常通过 keyup 函数来实现。 每当释放按键时,都可以调用一个函数来确保所有字段都是准确的,如果是这样,则以不引人注目的方式让用户知道。在您的情况下,除非所有字段都正确,否则您可以禁用提交按钮。

注意:您永远不应该使用该功能修改当前编辑的文本字段,或执行任何其他会给用户带来烦恼的事情;)

<小时/>

编辑:我修改了代码,以便在每次为所有输入字段抬起按键时进行验证。 我对 JQuery 不太熟悉,所以我用普通的 Javascript 来完成。如果需要的话,它应该很容易转换。

$(function(){


  var inputs = document.getElementsByTagName("input");

  for(var i = 0; i < inputs.length; i++) {

    inputs[i].addEventListener("keyup", function(){validate()}, true);

  }


  $('.error').hide();
  $(".cool-button").click(function(){validate()});

  function validate() {
                          $('.error').hide(); 
                          $("label#name_error").hide(); 
                          $("label#invalid_error").hide(); 
                          $("label#email_error").hide(); 
                          $("label#invalid_phone_error").hide(); 
                          $("label#phone_error").hide(); 
                          $("label#zip_error").hide(); 

                          var name=$("input#contact_name").val();
                          var email=$("input#contact_email").val();
                          var emailRegEx =/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/
                          var phone=$("input#contact_phone").val();
                          var phone=phone.replace(/\s+-/g, "");
                          var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/
                          var zip=$("input#contact_zip").val();
                          var best_time=$("input#contact_best_time").val();
                          var message=$("textarea#contact_message").val();
                          var timestamp=$("input#timestamp").val();

                          if(name==""){
                          $("label#name_error").show();$("input#contact_name").focus();return false;
                          }
                          if(email==""){
                          $("label#email_error").show();$("input#contact_email").focus();return false;
                          }
                          if (document.getElementById('contact_email').value.search(emailRegEx )==-1) {
                          $("label#invalid_error").show();$("input#contact_email").focus();return false;
                          }
                          if(phone==""){
                          $("label#phone_error").show();$("input#contact_phone").focus();return false;
                          }
                          if (document.getElementById('contact_phone').value.search(phoneRegEx )==-1) {
                          $("label#invalid_phone_error").show();$("input#contact_phone").focus();return false;
                          }
                          if(zip==""){
                          $("label#zip_error").show();$("input#contact_zip").focus();return false;
                          }
                          if(message==""){
                          $("label#message_error").show();$("textarea#contact_message").focus();return false;
                          }
                          else {
                          var dataString='contact_name='+name+'&contact_email='+email+'&contact_phone='+phone+'&contact_best_time='+best_time+'&contact_zip='+zip+'&timestamp='+timestamp+'&contact_message='+encodeURIComponent(message);
                          $.ajax({
                                 type:"POST",
                                 url:"php/contact.php",
                                 data:dataString,
                                 success:function(){$('#contact-form').html("<div id='message'></div>");$('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at info@wirecrafters.com or call us at 800-924-9473</p>").hide().fadeIn(800,function(){$('#message').append("<img id='checkmark' src='images/submit2.png' />");});}});
                          }
                          return false;
                          };
  });

关于Javascript 验证输入更改,仅在单击“提交”按钮时提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537409/

相关文章:

jquery - Dajaxice 表单验证 : "unicode object has no attribute get" (jquery serialize)

javascript - MVC Controller 方法不是从 ajax 调用的

jquery - 了解 $.validator.unobtrusive.adapters.addBool() 方法

jquery - 在JQuery验证库的远程规则中直接通过POST而不是GET发送参数?

JavaScript Promise 返回 Pending 但我只需要值

jquery - 通过 JQuery 验证插件单击同一 HTML 表单中的不同按钮来验证不同字段

javascript - 完整日历可定制标题

JavaScript 不区分大小写的数组通用排序

javascript - 通过 Lodash 对分组的对象进行排序

javascript - 使用javascript插入字母