通过jquery ajax验证并提交表单

时间:2013-07-17 04:13:59

标签: javascript jquery validation

我有以下jquery代码用于验证和表单的html代码。我想验证表单然后提交。这两段代码都正常工作,即验证和提交。问题是我应该如何组合代码,以便它可以首先验证表单然后提交它。

2 个答案:

答案 0 :(得分:0)

为了完成这项工作,我对您的脚本进行了一些更改。

$(document).ready(function(){
    //global vars
    var form = $("#subscribeForm");
    var name = $("#name");
    var email = $("#email");
    var nameInfo = $("#nameInfo");
    var emailInfo = $("#emailInfo");
    //On blur
    name.blur(validateName);
    email.blur(validateEmail);

    //On key press
    name.keyup(validateName);

     var value = $('#button input').val();
        var name1 = $('#button input').attr('name');

        $('#button input').remove();
        $('#button').html('<a href="#" class="cssSubmitButton" rel=' + name1 + '>' + value + '</a>');    

    //validation functions
    function validateEmail(){
        //testing regular expression
        var a = $("#email").val();
        var filter = /^(([^<>()[\]\\.,;:\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,}))$/;
        //if it's valid email
        if(filter.test(a)){
            email.removeClass("error");
            emailInfo.text("Valid E-mail please, you will need it to log in!");
            emailInfo.removeClass("error");
            return true;
        }
        //if it's NOT valid
        else{
            email.addClass("error");
            emailInfo.text("Type a valid e-mail please :P");
            emailInfo.addClass("error");
            return false;
        }
    }
    function validateName(){
        //if it's NOT valid
        if(name.val().length < 4){
            name.addClass("error");
            nameInfo.text("We want names with more than 3 letters!");
            nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else{
            name.removeClass("error");
            nameInfo.text("What's your name?");
            nameInfo.removeClass("error");
            return true;
        }
    }


   $('#button').on('click','a',function () {  

    var isValid = false;
    if(validateName() & validateEmail())
            isValid =  true
        else
            isValid =  false;

            //You can use default form submission or with the ajax call below
            //In this example, I'm using a dummy php call so that you can see the loading animation
            //$('form[name=' + $(this).attr('rel') + ']').submit();         

        if(isValid)
        {
         var link = $(this);

            $.ajax({
                url : 'load.php',
                data: '',
                type: 'GET',
                cache: 'false',
                beforeSend: function () {
                    link.addClass('loading');                   
                },
                success: function () {
                    link.removeClass('loading');
                    $('#button').css('display','none');     
                    $('#success').css('display','block');
                    alert('Submitted');
                },  
                error: function() {

                }       
            });
        }


        });

});

并在你的html中添加了一些id。

<form method="post" action="" id="subscribeForm" name="subscribeForm">
    <fieldset>
        <label>Name: </label><input type="text" class="effect" name="name" id="name">
        <span id="nameInfo">What's your name?</span>
    </fieldset>

    <fieldset>
        <label>Email: </label><input type="text" class="effect" name="email" id="email">
        <span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
    </fieldset>

    <div id="button">
        <input type="submit" value="Subscribe" name="subscribeForm"/>
    </div>
    <div id="success">
        <strong>Data Saved Successfully.</strong>
    </div>

答案 1 :(得分:0)

感谢您的回答,但即使我的代码正常运行。以下是工作代码。

Java脚本

<script type="text/javascript">
    /*<![CDATA[*/

    $(document).ready(function () {

        var value = $('#button input').val();
        var name = $('#button input').attr('name');

        $('#button input').remove();
        $('#button').html('<a href="#" class="cssSubmitButton" rel=' + name + '>' + value + '</a>');

        //global vars
        var form = $("#customForm");
        var name = $("#name");
        var nameInfo = $("#nameInfo");
        var email = $("#email");
        var emailInfo = $("#emailInfo");


        //On blur
        name.blur(validateName);
        email.blur(validateEmail);

        //On key press
        name.keyup(validateName);

        //On Submitting
        $('#button a').live('click', function () {                  

            var link = $(this);
            if(validateName() & validateEmail())
            {
                var link = $(this);

                $.ajax({
                    url : 'load.php',
                    data: '',
                    type: 'GET',
                    cache: 'false',
                    beforeSend: function () {
                        link.addClass('loading');                   
                    },
                    success: function () {
                        link.removeClass('loading');
                        $('#button').css('display','none');     
                        $('#success').css('display','block');
                        alert('Submitted');
                    },  
                    error: function() {

                    }       
                });

                return true
            }
            else
            {
                return false;
            }
        });


        //validation functions
        function validateEmail(){
            //testing regular expression
            var a = $("#email").val();
            var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
            //if it's valid email
            if(filter.test(a)){
                email.removeClass("error");
                emailInfo.text("Valid E-mail please, you will need it to log in!");
                emailInfo.removeClass("error");
                return true;
            }
            //if it's NOT valid
            else{
                email.addClass("error");
                emailInfo.text("Stop cowboy! Type a valid e-mail please :P");
                emailInfo.addClass("error");
                return false;
            }
        }
        function validateName(){
            //if it's NOT valid
            if(name.val().length < 4){
                name.addClass("error");
                nameInfo.text("We want names with more than 3 letters!");
                nameInfo.addClass("error");
                return false;
            }
            //if it's valid
            else{
                name.removeClass("error");
                nameInfo.text("What's your name?");
                nameInfo.removeClass("error");
                return true;
            }
        }
    });

    /*]]>*/
    </script>

CSS脚本。

<style type="text/css"> 
        body {
            font-family: arial;
            font-size:12px;
            margin:10px;    
            text-align:center;
        }

        form {
            margin:0 auto; 
            text-align:left;
            width:270px;
            border:1px solid #ccc;
            padding:15px;
            background:#fff;
            border-radius: 10px; 
            -moz-border-radius: 10px; 
            -webkit-border-radius: 10px; 
            box-shadow: 0 0 4px #ccc; 
            -webkit-box-shadow: 0 0 4px #ccc; 
            -moz-box-shadow: 0 0 4px #ccc;
        }

        fieldset {
            overflow:hidden;
            border:0;
            height:30px;    
            margin:3px 0;
        }

        fieldset label {
            display:block;
            width:50px;
            float:left;
            font-weight:700;
            color:#666; 
            line-height:2.2em;
        }

        fieldset input {
            float:left;
            border:1px solid #ccc;  
            height: 20px;
            padding:3px;
            width:190px;
            font-size:12px;
        }

        #button {
            margin-top:10px;
            padding-right:20px;
            text-align:right;   
        }

        #button input {
            margin:0 auto;
        }       

        a.cssSubmitButton {         
            font-size: 12px;
            background: #fff no-repeat 4px 5px;
            display: inline-block;
            padding: 5px 20px 6px;
            color: #333;
            border:1px solid #ccc;
            text-decoration: none;
            font-weight: bold;
            line-height: 1.2em;
            border-radius: 15px;
            -moz-border-radius: 15px;
            -webkit-border-radius: 15px;
            -moz-box-shadow: 0 1px 3px #999;
            -webkit-box-shadow: 0 1px 3px #999;
            position: relative;
            cursor: pointer;
            outline:none;
        }

        a.cssSubmitButton:visited {}

        a.cssSubmitButton:hover {
            border:1px solid #333;
        }

        .loading {
            background-image:url('load.gif') !important;
            color:#ccc !important;  
            -moz-box-shadow: 0 0 0 #fff !important;
            -webkit-box-shadow: 0 0 0 #fff !important;
        }

        .effect {
            border-radius: 5px;
            -moz-border-radius: 5px;
            -webkit-border-radius: 5px; 
        }
        #success{
            text-align:center;
            font-size:12px;
            margin-top:10px;
            display:none;
            color:#458B00;

        }
        #subscribeForm div span.error{
    color: #e46c6e;
}

#subscribeForm input.error{
    background: #f8dbdb;
    border-color: #e77776;
}

#subscribeForm span.error{
    color: #e46c6e;
}

    </style>

Html表格。

<form method="post" action="" id="subscribeForm" name="subscribeForm">
    <fieldset>
        <label>Name: </label><input type="text" class="effect" name="name" id="name" >
        <span id="nameInfo">What's your name?</span>
    </fieldset>

    <fieldset>
        <label>Email: </label><input type="text" class="effect" name="email" id="email" >
        <span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
    </fieldset>

    <div id="button">
        <input type="submit" value="Subscribe" name="subscribeForm"/>
    </div>
    <div id="success">
        <strong>Data Saved Successfully.</strong>
    </div>
</form>