Javascript check form onsubmit - javascript

I've used event.preventDefault() to stop the form action and call the login() , but when the login function return true, it still can't do the form action?
HTML:
<form onsubmit="event.preventDefault();return login();" action="index.php" method="get" id="register-form" >
Javascript:
<script type="text/javascript">
function login() {
var password = window.prompt("Please input password", "");
if (password !== '123') {
alert('Password is incorrect');
return false;
} else {
alert('Success');
return true;
}
}
</script>

Remove event.preventDefault(); from the onsubmit. This will stop the form submission regardless of the value returned from login().
Demo
function login() {
var password = window.prompt("Please input password", "");
if (password !== '123') {
alert('Password is incorrect');
return false;
} else {
alert('Success');
return true;
}
}
<form onsubmit="return login();" action="index.php" method="get" id="register-form">
<input type="submit" value="Login" />
</form>

Related

Returning false from onsubmit function doesn't prevent form from submitting

After I submit the form, the form will ignore the onsubmit whether the return is true or false, the form will directly go to form action.
I want to validate the input, if it is null it will remain on the same page and pop up an alert.
This is my JavaScript
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.loginform.userName.focus();
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.userform.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>
This is my form
<form action="Login" method="post" name="login" onsubmit="return validLogin();">
The userName field is miscased in the code
<script>
function validLogin() {
if (document.login.username.value == "") {
alert("Please enter Login Name.");
document.login.username.focus();//Here
return false;
}
if (document.login.password.value == "") {
alert("Please enter password.");
document.login.password.focus();
return false;
}
alert("Welcome User");
return true;
}
</script>

I'm having a cannot POST when attempting to submit a form with JS

I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}

HTML Form validation using Javascript / PHP

I have set up a basic contact form which emails the form data via PHP. This works fine but I am having trouble intregrating validation script into the code to prevent the form from submitting when no data is entered.
My code so far is:
PHP to Email the data:
<?php
//validate
if(isset($_POST['submit']))
{
$to="email#testemail.com";
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject="Contact Us";
$body="Name: $name \n\n Email Address: $email \n\n";
$sent=mail($to, $subject, $body);
echo 'Sent'; die;
}
//
?>
JS to post the form:
$(document).ready(function() {
$("#form1").validate({
submitHandler: function() {
//submit the form
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
$("#form1").serialize(),
function(data){
//if message is sent
if (data == 'Sent') {
$("#message").fadeIn(); //show confirmation message
}
//
});
return false; //don't let the page refresh on submit.
}
}); //validate the form
});
HTML Form
<div id="contact-form">
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="text" id="name" name="name"/>
<input type="text" id="email" name="email"/>
<input name="submit" type="submit" title="Submit" class="submit_go" value="Submit"/>
</form>
<div id="message">Thank you for your message</div>
</div>
I have tried integrating the below validation script but this doesn't prevent the form from submitting?
Validation Script
function leftValue(e, t, n) {
$(this).text(t.parent()[0].style.left)
}
$(document).ready(function() {
required = ["name", "email"];
email = $("#email");
errornotice = $("#error");
emptyerror = "Required Field";
emailerror = "Required Field";
$("#form1").submit(function() {
for (i = 0; i < required.length; i++) {
var e = $("#" + required[i]);
if (e.val() == "" || e.val() == emptyerror) {
e.addClass("form-error");
e.val(emptyerror);
errornotice.fadeIn(750)
} else {
e.removeClass("form-error")
}
}
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA- Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("form-error");
email.val(emailerror)
}
if ($(":input").hasClass("form-error")) {
return false
} else {
errornotice.hide();
return true
}
});
$(":input").focus(function() {
if ($(this).hasClass("form-error")) {
$(this).val("");
$(this).removeClass("form-error")
}
})
});
Aside of your validation in the client you really have to do the validation on the server side all over (in PHP). There is NO guarantee whatsoever that the client side validation happens (users might even have disabled javascript completely), nor that the input comes from your page at all.
Client side validation: eye-candy for the user
Server side validation: where the real security and protection happens.
FWIW: html5 allows for client side validation by the browser.
<form [...]>
<input type="text" id="name" name="name" required="required" placeholder="Name" minlength="2" />
<input type="email" id="email" name="email" required="required" placeholder="Email" />
<input name="submit" type="submit" title="Submit" class="submit_go" value="Submit" />
</form>
More info:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation
https://html.spec.whatwg.org/multipage/forms.html
It might just be as simple as $(":input").hasClass("form-error") > $("input").hasClass("form-error"). I don't see anything else that would prevent this from working.
Although I'd suggest another route. Instead of adding the class form-error to the inputs, then looking for inputs with that class at the end to determine if there was an error, why not just set a boolean flag saying there was an error. That way, there's no additional DOM lookup, which is an expensive operation.
$("#form1").submit(function() {
var isValid = true;
for (i = 0; i < required.length; i++) {
var e = $("#" + required[i]);
if (e.val() == "" || e.val() == emptyerror) {
e.addClass("form-error");
e.val(emptyerror);
errornotice.fadeIn(750);
isValid = false;
} else {
e.removeClass("form-error")
}
}
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA- Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("form-error");
email.val(emailerror);
}
if (!isValid) {
return false;
} else {
errornotice.hide();
return true;
}
});

javascript confirm cancel still submits form

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?');
}

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.
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.

Categories