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.
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();
});
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.
Related
I'm not able to redirect to a single page using windows location in .js page.
However I checked with alert box to see whether the condition is passing true or not and it is working while location is not working.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I feel I'm missing something.
I suspect you're calling validate like this:
<form onsubmit="validate()" ...>
That won't use the return value of validate to cancel the submit. You need a return:
<form onsubmit="return validate()" ...>
Since the submission is not being cancelled, the form submission is a navigation action, which overrides your assignment to window.location.href.
In a comment you've said you're doing this:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
If so, adding the return to the onclick should fix it on any modern browser:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
But I would move it to an onsubmit on the form instead.
Side note: There's no need for the type="submit" on that button. submit is the default type for button elements.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1#gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
return false; // ALWAYS return this. else it will proceed with page submit.
}
}
I want to check some forms values before submit it. So I put this into my :
<form name="frmcontact" id="frmcontact" method="post" action="<?php echo($action);?>" class="forms" onsubmit="return checkContactsFields()">
And here is my JS function :
function checkContactsFields(){
var newIdValue = document.forms["frmcontact"]["new_id"].value;
if(newIdValue !== 'ADRESSE NON IDENTIFIE'){
var form = document.forms["frmcontact"].elements;
for(var i = 0; i < form.length; i++) {
if(form[i].name === 'street' || form[i].name === 'cp' || form[i].name === 'town'){
if(form[i].value === ''){
console.log('ok');
document.getElementById('main_error_popup').style.display = 'table-cell';
if(form[i].name === 'street')
errorMsg = 'Voie';
else if(form[i].name === 'cp'){
errorMsg = 'Code Postal';
}else{
errorMsg = 'Ville'
}
document.getElementById('main_error_popup').innerHTML = 'Le champ ' + errorMsg + ' est vide';
return false;
}
}
}
return true;
}
return true;
}
The problem I have is that even with the return false statement, the form is submit..
Any idea of the reason ?
Thanks in advance
Add preventDefault to the function & submit the form using ajax
In html
onsubmit="return checkContactsFields(event)"
in js
function checkContactsFields(e){
e.preventDefault()
}
A quick test in chrome seems to work if I
just do :
function checkContactsFields(){
alert("I won't submit");
return false;
}
https://plnkr.co/edit/yA3hVlDtfUGxSCceqPMY?p=preview
If your javascript throws an error during execution the submit will still happen.
What does your html look like?
//this is the javascript program for validation
function validateForm()
{
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
boolean valid = true;
if(password != conpass)
{
alert("password is not same");
valid=false;
}
else if(name==null || name=="")
{
alert("User Name should not be blank..");
valid=false;
}
else if(password==""|| password==null)
{
alert("Password should not be blank");
valid=false;
}
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
};
//and this is the html in which I am using this but it is not working properly,it is not taking the js validation and directly forwarding me to the reg.jsp page.
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
In order to prevent submit via javascript, you have to return false in your onsubmit handler.
So the in the following line the validateForm() must return false:
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
You have many if-else blocks that set the var valid = false and this is ok.
But this valid variable should be returned. You do this only in the last else blocks.
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
The previous checks are just preparing the variable, but don't return it.
And this is what you need to do.
Here is an example how it can be done:
function validateForm() {
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
var valid = true;
var message = "everything is valid";
if(password != conpass)
{
message = "password is not same";
valid = false;
}
else if(name==null || name=="")
{
message = "User Name should not be blank..";
valid = false;
}
else if(password==""|| password==null)
{
message = "Password should not be blank";
valid = false;
}
else if(!this.form.checkbox.checked)
{
message = "You must agree to the terms first.";
valid = false;
}
alert(message);
return valid;
};
Other improvement could be:
Reordering the conditions by descending importance.
For example: if the Term are not accepted, is not important, if the password is empty.
If password is empty, it is not important, if the conpass is the same.
Using html5, which hast more input types and adjustable build-in validation for common cases. See more here: http://html5doctor.com/html5-forms-input-types/
I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}
I am facing the problem when i submit the form by input type button here is my code :
<form method="POST" id="eulaForm" action="downloadPack.php?packId=<?php echo $_REQUEST['packId'];?>" enctype="multipart/form-data">
that is my form, which looks fine to me. in that form, i put this button:
<input name="declineBtn" id="declineBtn" value="Decline" type="button" class="back">
<script type="text/javascript">
$(document).ready(function(){
$('#declineBtn').click( function() {
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); } else { return true;}
});
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
</script>
and as you can see, it calls $('#eulaForm').submit(); , but the form is not submitting (ie. the page is not refreshing). why is that?
thanks!
try like this:
wrap up chgAction() inside document ready and add preventDefault()
$(document).ready(function(){
$('#declineBtn').click( function(e) {
e.preventDefault();
searchTxt = $('#searchText').val();
// ajax logic to test for what you want
if (searchText != '') { return chgAction(searchTxt); }
else { return true;}
});
function chgAction(cmpText)
{
if(cmpText != '')
{
$('#eulaForm').attr('action', 'searchResult.php');
alert("After - action = "+$("#eulaForm").attr("action"));
//submit the form
$('#eulaForm').submit();
return false;
}
else{
url = '<?php
echo basename($_SERVER['HTTP_REFERER']);?>';
window.parent.location.href = url;
//parent.history.back();
return false;
}
}
});