开发者

Form submission will not stop for validation

开发者 https://www.devze.com 2023-04-10 14:05 出处:网络
What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.

What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.

<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data"> ...

<input type="image" id="submit" name="submit" src="submit.png" border="0" />

JS email validation:

//$("#rfq").submit(function() { doesnt seem to work ei开发者_如何学Pythonther

$('#submit').click(function() {
    var email = $('#email').val();
    if(email.indexOf("@") == -1){
        $("#email").addClass('invalid');
        return false; // cancel form submission if email invalid
    }
    return false; // return true if no errors once i get it working
});


Working Example

First, make sure all event handlers are attached once the DOM is "ready"

I'm using .submit() on the actual form.

$(document).ready(function() {
    // now that document is "ready"
    $('#formId').submit(function() {
        var email = $('#emailInput').val();
        alert(email);
        if(email.indexOf("@") == -1){
            alert("invalid!");
            return false; // cancel form submission if email invalid
        }
        alert("valid!");
        return true; // return true if no errors once i get it working 
    });
});


Try wrapping your code in a ready block.

$(document).ready(function(){
    // your code here
});

You should also be using the submit event on the <form> element, I think.


This is going to work. If you don't understand why, feel free to ask :)

var validated = false;

$(document).ready(function(){
    $("#rfq").submit(function(event) {
        if (validated === true) {
            return true;
        }
        event.preventDefault(); // prevent submission
        var email = $('#email').val();
        if(email.indexOf("@") == -1){
            $("#email").addClass('invalid');
            return;
        }
        validated = true;
        return $(this).trigger('submit');
    });
});


You could try using this function to validate your address.

function validateEmail(elementValue){
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue);
 }

And then modify your code to submit the form.

$('#submit').click(function() {
    var email = $('#email').val();
    if(!validateEmail(email)){
        $("#email").addClass('invalid');            
    }
    else {
       $("form").submit();
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消