2

I am trying to validate a simple form before the php process. When I let every input empty, the form is stopped, but if I stay on the same page and fill every inputs, the form won't submit.

I guess the return false; stays at the first validation. I'm a beginner :)

So here is an excerpt:

HTML

<input onblur="validName();" type="text"  name="name" id="name">
<textarea id="message" name="message" onblur="validMess();" rows="5"></textarea>

<input type="submit" name="submit" onclick="validSubmit();" value="send">

JQUERY

function validSubmit() {
var message = $("#message").val();
var name = $("#name").val();

    if( name == ''){
        $("#valid-name").removeClass('hide'); // if empty = show error message
        $("#form").submit(function(e){
            return false;
        });
    }
    else {
        $("#valid-name").addClass('hide'); // all good = hide error message
        $("#form").submit(function(e){
            return true;
        });
    }


    if(message == ''){
        $("#valid-mess").removeClass('hide'); // if empty = show error message
        $("#form").submit(function(e){
            return false;
        });
    }
    else { 
        $("#valid-mess").addClass('hide'); // all good = hide error message
        $("#form").submit(function(e){
            return true;
        });
    }

}

IDs : valid-name and valid-mess are two error messages set to display: none; by default.

I'm a bit lost, the answer can be in JS or Jquery I don't mind.

Thank you for your time.

1 Answer 1

2

Don't call submit from the submit callback, just return false when it's not OK :

function validSubmit() {
    var message = $("#message").val();
    var name = $("#name").val();
    $("#valid-name,#valid-mess").addClass('hide');
    var ok = true;
    if (name == ''){
        $("#valid-name").removeClass('hide');
        ok = false;
    }
    if (message == ''){
        $("#valid-mess").removeClass('hide');
        ok = false;
    }
    return ok;
}

Also, as noted by Barmar, this isn't the best way to bind the validation. Instead of binding to the click event, you'd better use

$('#id_of_the_form').submit(validSubmit);
Sign up to request clarification or add additional context in comments.

2 Comments

You should also call validSubmit() in the form's onsubmit handler.
Yep, it works perfectly, thank very much to you two ! I owe you a beer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.