如何在用户键入时动态清除表单错误

时间:2013-12-03 17:00:29

标签: jquery

我有一个使用AJAX的联系表单。

目前,当用户最初未在任何必填字段中输入信息时,会出现错误消息。要清除该错误消息,用户必须单击“发送”按钮。

我想要做的是:如果用户没有为任何必填字段输入任何信息,但随后开始输入并满足该字段的要求,则错误消息应自动清除,而不是必须单击“发送” '再次按钮使错误信息消失。

这是我的代码:

$(document).ready(function() {
    $('form #response').hide();


    $('.button').click(function(e) {

        e.preventDefault();

        var valid = '';
        var required = ' is required.';
        var first = $('form #first').val();
        var last = $('form #last').val();
        var email = $('form #email').val();
        var message = $('form #message').val();
        var tempt = $('form #tempt').val();
        var tempt2 = $('form #tempt2').val();

        if (first = '' || first.length <= 1) {
            valid += '<p>Your first name' + required + '</p>';
        }

        if (last = '' || last.length <= 1) {
            valid += '<p>Your last name' + required + '</p>';
        }

        if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
            valid += '<p>Your email address' + required + '</p>';
        }

        if (message = '' || message.length <= 4) {
            valid += '<p>A message' + required + '</p>';
        }

        if (tempt != 'http://') {
            valid += '<p>We can\'t allow spam bots.</p>';
        }

        if (tempt2 != '') {
            valid += '<p>A human user' + required + '</p>';
        }

        if (valid != '') {
            $('form #response').removeClass().addClass('error')
                .html('' +valid).fadeIn('fast');
        }

        else {
            $('form #response').removeClass().addClass('processing').html('Sending...').fadeIn('fast');

            var formData = $('form').serialize();
            submitForm(formData);
        }

    });

});

function submitForm(formData) {

    $.ajax({

            type: 'POST',
            url: 'mail/mailform.php',
            data: formData,
            dataType: 'json',
            cache: false,
            timeout: 4000,
            success: function(data) {

                            $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
                                            .html(data.msg).fadeIn('fast');

                            if ($('form #response').hasClass('success')) {
                                setTimeout("$('form #response').fadeOut('fast')", 4000);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {

                        $('form #response').removeClass().addClass('error')
                                    .html('<p>There was an <strong>' + errorThrown +
                                        '</strong> error due to an <strong>' + textStatus +
                                        '</strong> condition.</p>').fadeIn('fast');
                    },
                    complete: function(XMLHttpRequest, status) {

                        $('form')[0].reset();
                    }

          });


};


var required = ' is required.';
        var first = $('form #first').val();
        var first = $('form #first').keyup(function (event) {
        var first = $(this);
        if ($first.val() !== ''){
            $('form #response2').removeclass('response2');
        }
        });

1 个答案:

答案 0 :(得分:0)

1 - 首先,从按钮中删除验证,将其设置为单独的函数,因为这样您可以使用验证,而不仅仅是按下按钮,如:

function IsValidForm() {

        e.preventDefault();

        var valid = '';
        var required = ' is required.';
        var first = $('form #first').val();
        var last = $('form #last').val();
        var email = $('form #email').val();
        var message = $('form #message').val();
        var tempt = $('form #tempt').val();
        var tempt2 = $('form #tempt2').val();

        if (first = '' || first.length <= 1) {
            valid += '<p>Your first name' + required + '</p>';
        }

        if (last = '' || last.length <= 1) {
            valid += '<p>Your last name' + required + '</p>';
        }

        if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
            valid += '<p>Your email address' + required + '</p>';
        }

        if (message = '' || message.length <= 4) {
            valid += '<p>A message' + required + '</p>';
        }

        if (tempt != 'http://') {
            valid += '<p>We can\'t allow spam bots.</p>';
        }

        if (tempt2 != '') {
            valid += '<p>A human user' + required + '</p>';
        }

        if (valid != '') {
            $('form #response').removeClass().addClass('error')
                .html('' +valid).fadeIn('fast');

            return false;
        }

        else {
          return true;
        }

}

注意结尾,如果它向用户return false;抛出一些错误(无效),如果一切正常return true;

2 - 其次,现在您必须在用户在字段中键入时设置验证。 确保代码在验证输入下,或者在onRead()函数内。

$( document ).ready(function() {

    $( ".validationField" ).keydown(function() {
       //valid form when user enter data to "validationField" fields
       IsValidForm();
    });

});

将“validationField”类添加到要在用户输入时验证的字段,例如:

<input type="text" id="email" class="validationField" />

有!现在这可以实现你想要的,你只需要改变你的发送按钮:

$('.button').click(function(e) {
    e.preventDefault();

    if(IsValidForm())
    {
         $('form #response').removeClass().addClass('processing').html('Sending...').fadeIn('fast');

        var formData = $('form').serialize();
        submitForm(formData);

    }

});

现在,你可以意识到它会在第一个用户类型上有效,对吗?如果您只想在第一次表单发送后开始验证,则需要创建一个变量:

var hasSubmited = false;

并在表单发送按钮中设置:

$('.button').click(function(e) {
    e.preventDefault();

    hasSubmited = true;
    ...

并在您的整个IsValidForm()验证函数中,封装验证检查此变量是否为真,您只是一个快速的方法:

function IsValid() {

        e.preventDefault();

        if(hasSubmited == false) return true;

        ...

现在只有在第一次提交表单后才会验证。