Aimad MAJDOU
Aimad MAJDOU

Reputation: 233

prevent the user from submitting

I want to prevent the user from submitting data in a form, but when I test it with JavaScript it's not returning true.

this is the submit button :

    input type="submit" value="S'inscrire" name="inscrire" onsubmit="return Verifier(this.form);">

and this is the code for the JS test function :

 function Verifier()
        {
            var mdp1 = document.form.mdp.value,
                        mdp2 = document.form.confirmer.value,
                        email = document.form.email.value,
                        pseudo = document.form.pseudo.value;

            var testMdpIdentique = (function() {

                    if(mdp1 == mdp2) return true;
                    else return false;
                 })();


            if(!testMdpIdentique || mdp1 == "" || mdp2 == "" || email == "" || pseudo== "" )
            {
                alert ('Il faut remplir tous les champs');
                return false;
            }
            return true;

        }

the problem is that it's submitting information even if the test is not valid, I tried to try an alert message in the Valider function but it didn't worked.

Upvotes: 0

Views: 69

Answers (2)

pravat
pravat

Reputation: 475

I think the below code is syntactically incorrect.

var testMdpIdentique = (function() {

                if(mdp1 == mdp2) return true;
                else return false;
             })();

Replace with

var testMdpIdentique = function() {

                if(mdp1 == mdp2) return true;
                else return false;
             };

Also you don't need to pass (this.form) in the onClick event. Generally submit button submits the form is there is a syntax error in your onClick callback method.

Upvotes: -1

Vitthal
Vitthal

Reputation: 546

In normal Javascript

you can use return value of function to prevent form submission

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

In DOJO

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

Upvotes: 2

Related Questions