在点击事件之前仅显示几秒钟

时间:2018-06-24 18:54:08

标签: jquery

我正在尝试验证用户输入的内容,并且(如果输入不正确)显示错误消息。但是,错误消息仅显示几秒钟,然后消失。
为什么?

var errorMessage = "";

var pattern = /^([a-z\d!#$%&'*+\-\/=?^_ {|}〜\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF] +(.. [az \ d!#$%&'* +-/ =?^ _ { {1}}

{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;

1 个答案:

答案 0 :(得分:0)

对我来说,您正在尝试验证联系表单,这与在“ #emailSubmit”按钮上添加了两个事件侦听器一样。

这是我的建议

假设您具有此html标记, 这就是我如何以简单的基本方式验证表单的方法。

(function() {


  $('#submitContactForm').on('click', function(event) {
  
    event.preventDefault();
    
    validateForm();
    
  });
  
  
  var validateForm = function() {    
    
    var email    = $('#email').val();
    var subject  = $('#subject').val();
    var body     = $('#body').val();

    var errors   = [];

    if(! isEmailValid(email)) {
        errors.push('Email is not valid');
    }

    if(! subject) {
        errors.push('Suject is required.');
    }

    if(! body) {
        errors.push('Body is required');
    }

    if(errors.length) {

        var $alert = $("#errorAlert");
        
        $alert.html('');

        errors.forEach( function(error_message, index) {
            $alert.append('<p>'+error_message+'</p>');
        });

        $alert.show();

    } else {

        $('#contactForm').submit();
    }
  };
    
    
  var isEmailValid = function(email) {

    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        
    return re.test(email);
  };

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="alert alert-danger alert-dismissible" style="display:none;" id="errorAlert"></div>

<form action="my-action" method="post" id="contactForm">

    <input type="email" name="email" id="email">
    
    <input type="text" name="subject" id="subject">
    
    <textarea name="body" id="body" cols="30" rows="10"></textarea>

    <button type="submit" id="submitContactForm">Submit</button>

</form>