0

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.

2
  • 1
    Why is testMdpIdentique assigned a self-invoking function expression? Commented Mar 15, 2013 at 19:26
  • 1
    You could simply write var testMdpIdentique = (mdp1 == mdp2); Commented Mar 15, 2013 at 19:33

2 Answers 2

2

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(); }); 
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

-1 - Doesn't really address the problem, and you're changing testMdpIdentique from a Boolean to a function object which would no doubt affect the rest of the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.