简体   繁体   中英

Client-side validation is not posting values

I have a form that validates a value at a time. When all the values are validated and correct my ajax post function does not want to post. I would like to post when all the values are correct. One text field has a name, the last text field is an email.

Please check my jsFiddle and the code below.

HTML:

<form enctype="multipart/form-data" method="post" id="myform" name="myform_1">
    <input type="text" value="" id="name" name="myname" />
    <input type="text" value="" id="email" name="myemail"/>
    <input type="submit" value="Valid" id="validate" name="validate"/>
</form>

Javascript:

 $(document).ready(function(){
     function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min )
        {
            o.css("background-color","#F30");
            return false;
        }
        else
        {
            o.css("background-color","#FFF");
            return true;
        }
    }

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) )
        {
            o.css("background-color","#F30");
            return false;
        }
        else
        {
            o.css("background-color","#FFF");
            return true;
        }
    }

    //Click action
    $("#validate").click(function()
    {
        var name = $( "#name" );
        var email = $("#email");
        var valid = true;
        emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

        valid = valid && checkLength( name,"Please enter a name",3,6);
        valid = valid && checkRegexp( name, /^[a-z]([A-Z_\s])+$/i, "Name may consist of a-z, and 3 or more characters." );
        valid = valid && checkLength( email, "email", 6, 80 );
        valid = valid && checkkRegexp( email, emailRegex, "eg. ui@jquery.com" );
        //Email
        //alert ($("#myform").serialize());
        //End of Email

        if(valid)
        {
            var request = $.ajax({
                url: "inc/newsletter.php", // Ofcourse this would be your addLike.php in your real script
                type: "POST",
                data: $("#myform").serialize()
            });
            request.done(function(msg) {
                alert("Your details have been saved");
                location.reload();
            });

            request.fail(function(jqXHR, textStatus) {
                alert( "Request failed: " + textStatus );
            });

            return valid;
        }
        else
        {
            alert("No;")
        }
    });
});

Your submit event handler is not returning false, hence it is posting the form completely. First, make sure the event bubbling is stopped in the click handler in the following manner:

$("#validate").click(function(event)
{
       //YOUR AJAX CALL
       //RETURN SHOULD ALWAYS BE FALSE FOR AJAX SUBMISSION WHEN CALLED FROM TYPE BUTTON
       event.preventDefault();
       event.stopPropagation();
       return false;
})

You can then trace if the ajax call happens in the browser console...

Hope it helps!

Friend, youre calling this function "checkkRegexp" that doesnt exist!!

And you should return false at the end of youre function to prevent the form submission if some validation goes wrong!

You should also have a look at "parsley". This will help you with form validations.

Change the start of your function like this

$("#validate").click(function(e){
  e.preventDefault();
  //Rest of your function
}

e.preventDefault() is not cross browser compatible and might break in older browsers. Use the following if you support older browsers

if(e.preventDefault()!=undefined){
   e.preventDefault();
}else{
   e.returnValue = false;
}

If you are interested in knowing why your approach is not working. The button you are clicking is a submit button and you are not preventing it default behavior. This is the reason that form is submitted even though your form fields are incomplete.

Point to note is still ajax cal won't be called in example provide but it will be natural form refresh.

Solution provided will stop default action and will give full control to your ajax request and validations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM