Why does this form submit on click of the submit button - javascript

<script type="text/javascript">
var geid = function(x) {
var element = document.getElementById(x);
return element;
}
function submitForm(){
var password = geid('password').value;
var passwordConfirm = geid('passwordConfirm');
//THIS IS OF HIGH IMPORTANCE THAT THIS CONFIRM PASSWORD MATCHES
//WILL NEED TO VALIDATE IT IN THE PHP AS WELL>
else if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
else if (passwordConfirm == "") {
registerMessage.innerHTML = "Please confirm your password.";
return false;
}
else if (passwordConfirm != password) {
registerMessage.innerHTML = "Your passwords don't match.";
return false;
}
else {
registerMessage.innerHTML = "Taking you to your profile, please wait a moment...";
document.forms['registerform'].submit();
}
}
<form method="post" action="register.php" id="registerform" onsubmit="return submitForm()">
<label for="password" class="registerLabel">Password</label>
<input type="password" name="password" id="password" class="registerText" /> <br />
<label for="passwordConfirm" class="registerLabel">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm" class="registerText" /> <br />
<div class="submitMessage">
<input type="submit" id="submit" name="submit" value="Register" class="registerButton cleangray" /><br />
<div id="registerMessage"><?php echo $error ?></div>
</div>
<div class="clear"></div>
</form>

You can't start with else if; you need to start with if
if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
That's preventing any of your validation code from running and just submitting the form using the standard submit mechanism.
This also isn't the best way to approach the validation. Rather than return at each error, you could build up a string of messages and report them all back in one go. That way the user knows everything that's wrong — your current method will only ever set one message.

Because you have error in JavaScript, you are using else if without defining if first. Because of this error all JavaScript code fail.
Change
else if (password == ""){
to
if (password == ""){
Working demo http://jsfiddle.net/Zs3km/
BTW in your code HTML is within <script> tag, not sure if its your mistake just here. You have to close <script> tag before <form> tag is opened.

Related

Can I Validate Two Fields Instead of One Field With This JavaScript?

I use the javascript below to validate the Phone Number field on my form by showing the next hidden field whenever the value the user inputs in the phone number field on my form matches with the values in my javascript.
however, if their input does not match with the values in my javascript, the hidden field remains hidden and the user will be unable to submit the form.
The javascript works fine for the phone field but I am trying to validate two different fields to match with the values in my javascript.
For example, I want to make the values users input on the phone field and the email field of my form match with the values in my javascript before the hidden field shows.
Illustration below;
Lets say, the values in my javascript are; if (phone === "12345" && email === "12345#gmail.com")
If the user inputs Phone: 12345 and their email: 12345#gmail.com, the hidden field shows.
If the user inputs Phone:123 and their email: 12345#gmail.com, the hidden field remains hidden.
I have tried different solutions to validate the phone and email field but all my solutions failed and I need some help with this.
Sorry if my solution below is poor but I am not the owner of the original code.
Thanks for your help.
Below is my sample code for the phone field validation. (WORKING FINE!)
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isPhoneInUse(value)) {
$(".validate").show();
} else {
alert ("Phone do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone").val();
if (isPhoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return false;
}
})
function isPhoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
Below is my solution to validate the phone and email fields. (NOT WORKING!)
$('.validate').hide();
$('body').on('blur', '#phone', '#email', function() {
var value = $(this).val();
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
$(".validate").show();
} else {
alert ("Phone and Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone" && "#email".val());
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
// validation failed. cancel the event
console.log("not submitting");
event.preventDefault();
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
After many corrections, here is a working snippet:
$('.validate').hide();
$('#phone, #email').on('change', function() {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
$(".validate").show();
} else {
alert ("Phone or Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#theForm').on('submit', function(e) {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
// validation failed. cancel the event
console.log("not submitting");
e.preventDefault();
return false;
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="theForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>

Javascript - A problem with the validation of my form

I have a problem with the validation script of my php form to send an email, and although it works very well to validate the form, when the user clicks on the "accept" button of the alert, the script does not block the action, and the form is sent anyway...
What am I doing wrong?
Thanks in advance!
HTML:
<div id="form">
<section>
<form action="send.php" method="post" accept-charset='UTF-8'>
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">
</div>
</form>
</section>
</div>
SCRIPT (validation):
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
}
Change the event to onsubmit and put it on the form.
function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+#\w+\.+\w/;
if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}
else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}
else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
console.log('passed!');
}
<div id="form">
<section>
<form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>
<input id="submit" type="submit" name="submit" value="SEND">
</form>
</section>
</div>

i am not able to validate the captcha whether it is wrong or right using Javascript

This is Javascript
<script>
function q_form_val() {
var patt = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var captcha_entered = document.getElementById("captcha_entered").value;
if (captcha_entered == "") {
alert("Please enter the Captcha");
return false;
}
return true;
}
</script>
This is HTML code
<div class="row">
<div class="form-group">
<label class="control-label col-sm-3"><font color="#FF0000">*</font><strong>Captcha</strong>
</label>
<div class="col-sm-3">
<?php echo '<img src="captcha.php" alt="captcha">'; ?>
<br/>
<span><input name="captcha_entered" type="text" class="form-control" id="captcha_entered" size="27" maxlength="4"/></br></span>
<input type="hidden" name="captcha_total" id="captcha_total" value="<?php echo $_SESSION['rand_code']; ?>">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="col-sm-12">
<center>
<script type="text/javascript">
document.write("<input type=\"submit\" value=\"Submit\" class=\"btn1\"/>");
</script>
<noscript>
<p style="color: red;"><b><i>Please enable JavaScript to continue</i></b>
<p>
</noscript>
</center>
</div>
</div>
i am able to check the captcha whether it is empty or not
but i am not able to check whether it is wrong or right captcha
i think i should add more code in javascript for verfiying whether it is wrong or right?
The question is whether you should verify a captcha using Javascript. The whole purpose of a captcha is to circumvent automated scripts, but including the answer in the HTML makes it incredibly easy to bypass.
You should verify the captcha on the server, either through a form submit or AJAX request.
You should use RegExp.test(). It will return true/false if the passed in string passes a test of the pattern
function q_form_val() {
var patt = new RegExp(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
var captcha_entered = document.getElementById("captcha_entered").value;
if (captcha_entered == "") {
alert("Please enter the Captcha");
return false;
}else if(!patt.test(captcha_entered)){
alert("Bad Captcha Match");
return false;
}
return true;
}
EDIT
If you're actually trying to compare to the value of your hidden field to what was entered (the code about regex is not useful), and you would use the following code:
function q_form_val() {
var captcha_entered = document.getElementById("captcha_entered").value;
var captcha_total = document.getElementById("captcha_total").value;
if (captcha_entered == "") {
alert("Please enter the Captcha");
return false;
}else if(captcha_total !== captcha_entered)){
alert("Bad Captcha code");
return false;
}
return true;
}

Angular: unable to avoid form submit on validation failure

Im trying to validate the following form:
<div ng-controller="LoginController">
<form name="form" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate>
{{ errorUsername }}
<input id="username" name="username" type="text" placeholder="EMAIL ADDRESS" ng-model="username" required>
{{ errorPassword }}
<input id="password" name="password" type="password" placeholder="PASSWORD" ng-model="password" required>
<p><input name="commit" value="LOGIN" ng-click="submitForm()" type="submit"></p>
</form>
</div>
With the following method on LoginController:
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
};
if (! is_valid ) { $scope.form.submitted = true }
};
The form submition enters the method, and for a second you can see the the error messages are displayed. But the form is still submited.
I should add that the form is linked to a rails controller. But that shouldn't matter because my intention is never to call rail's controller action if the form has errors.
Thanks in advance.
All you need is to write return false;
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
return false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
return false;
};
if (! is_valid ) { $scope.form.submitted = true }
};
Try to replace
<input name="commit" value="LOGIN" ng-click="submitForm()" type="submit">
to
<input name="commit" value="LOGIN" ng-click="submitForm()" type="button">
You can try with this.
<form name="yourform" ng-submit="yourform.$valid && submitForm()"
This is is. Apparently you can't prevent default submit if the form has an action attribute:
Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
So, you have to trick it by adding some code in the form:
<form name="login" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate ng-submit="(submitted=true) && login.$invalid && $event.preventDefault()" ng-class="{true:'submitted'}[submitted]">
Basically we used $event.preventDefault() to stop the submit propagation only if the form is invalid; plus we set a $scope variable ‘submitted’ to true in order to have a class that gets appended to the form if the form has been submitted in an invalid state at least once, even if none of its fields have been ‘touched’ – so it’s still ng-pristine.
Solution found here: http://sandropaganotti.com/2014/03/01/angular-js-prevent-an-invalid-form-submission/

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Categories

Resources