表单在验证后提交密钥,而不是onclick

时间:2014-11-07 17:27:12

标签: javascript ajax

这是一个JSFiddle,它将显示我遇到的问题。

目前,只要数据经过验证,表单数据就会在密钥上提交,只有在点击“订阅”按钮时才能提交数据。

所以表单应该像这样工作。如果用户单击订阅按钮,并且特定输入未通过验证,则应显示该错误。如果用户随后更正了错误,则该特定错误应该在密钥上清除,但是,在表单实际提交任何数据之前,用户必须单击“订阅”,或者再次检查验证。目前,表单在通过验证后提交密钥,但情况并非如此。

除了在点击时提交数据外,我想知道如何验证(不提交数据)keyup,以及点击验证。

http://jsfiddle.net/cqf8guys/5/

代码:

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


$('.txt1').on('keyup click', function(e) {


e.preventDefault();

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


if(first=='' || first.length<=1) {
    $('form #first').css('border','2px solid #ff0000');
    $('form #first').css('background-color','#ffcece');
    valid += '<p>Your first name is required</p>';
}
else {
  $('form #first').removeAttr('style');
}

if(last=='' || last.length<=1) {
    $('form #last').css('border','2px solid #ff0000');
    $('form #last').css('background-color','#ffcece');
    valid += '<p>Your last name' + required + '</p>';
}
else {
  $(this).removeAttr('style');
}

if(city=='' || city.length<=1) {
    $('form #city').css('border','2px solid #ff0000');
    $('form #city').css('background-color','#ffcece');
    valid += '<p>Please include your city</p>';
}
else {
  $('form #city').removeAttr('style');
}

if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
    valid += '<p>A valid E-Mail address is 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 #response2').removeClass().addClass('error2')
        .html('' +valid).fadeIn('fast');
}

else {
    $('form #response2').removeClass().addClass('processing2').html('<p style="top:0px; left:0px; text-align:center; line-height:1.5em;">Please wait while we process your information...</p>').fadeIn('fast');

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

});

});

function submitFormSubscribe(formData) {

$.ajax({

type: 'POST',
url: 'http://3elementsreview.com/blog/wp-content/themes/3elements/php-signup/sign-up-complete.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 4000,
success: function(data) {

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

if ($('form #response2').hasClass('success2')) {
setTimeout("$('form #response2').fadeOut('fast')", 6000);
}

},
error: function(XMLHttpRequest, textStatus, errorThrown) {

$('form #response2').removeClass().addClass('error2')
.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();
}   
});

};

1 个答案:

答案 0 :(得分:0)

这是因为您已将功能附加到错误的事件侦听器类型。您不希望$('.txt1').on('keyup click', function(e) {...这就是为什么当您取消选择某些内容时它会变得混乱的原因。相反,你想要像这样的提交事件监听器....

$('.txt1').on('submit', function(e) {...$('.txt1').submit(function(e) {...

然后,如果验证失败,您可以执行e.preventDefault();并且不会提交表单。

以下是不使用您自己的代码的示例...

<强> JAVASCRIPT

var zipSwitch = false;

$(function() {
    zipValidate();
    validateForm(); //Add Form Submit Validation Event

});

//Constantly Monitor Validation
function zipValidate() {
    $("#zip").keyup(function() {
        var zipInput = $("#zip").val();

        if($.isNumeric(zipInput)) {
            $("#msgZone").html("Zip is correct");           
            $("#msgZone").attr("style", "border-color: rgb(4, 255, 17)");
            zipSwitch = true;

        } else {
            $("#msgZone").html("Zip must be numbers only. Please remove letters.");
            $("#msgZone").attr("style", "border-color: rgb(250, 20, 10)");
            zipSwitch = false;

        }

    });
}

//Allow Form To Submit or Not Depending on Validation
function validateForm() {
    $("#form1").submit(function(e) {

        //If Form Validation Was Correct
        if(zipSwitch==true) {

            var validCountry = countryValidationFunction();

            if(validCountry==true) {
                alert("Form Submitted Successfully");

            } else if(validCountry==false) {
                alert("Please Enter a Valid Country");
                e.preventDefault();
            }

        } else {
            e.preventDefault();
        }

    });


 }

<强> HTML

<form name="form1" id="form1" action="#" method="POST" class="span12" style="margin-top: 50px;">
    <div id="msgZone" class="well">
        Validation Message Zone
    </div>

    <div class="controls-row">                                                                      
        <span class="help-inline control-list">Zip:</span>
        <input id="zip" name="zip" type="text" class="input-medium" required="true" />
    </div>      
    <hr />


    <div class="controls-row">
        <button type="submit" id="btnSubmit" class="btn btn-success" onSubmit="validateForm()">Submit</button>
        <button type="reset" class="btn btn-danger">Reset</button>
    </div>
    <hr />

</form>