JavaScript Form Validation when false - javascript

This is really bothering me. I just want the form to not submit if the function returns false. Here is the script.
function checkPass(){
var pass1 = document.getElementById('pass');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirmMessage');
var goodColor = "#224466";
var badColor = "#900000";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
return true;
}else{
pass2.style.backgroundColor = badColor;
return false;
}
}
The form still submits when I use:
<form onsumbit="checkPass();">
</form>
and when I use:
<form>
<input type="submit" onclick="checkPass();">
</form>
and no luck. Any ideas?

Use this on the onsubmit event of your form:
onsubmit="return checkPass()"
Or this one for your Submit button (the input tag):
onclick="return checkForm()"

If you are using xhtml make sure 'onsubmit' is lowercase.
<form onsubmit="return checkPass()" ... >

As M2X says, you need to use
<form onsubmit="return checkPass();">
The reason is that when you assign an event handler as an attribute that way, what actually happens internally is that a new anonymous function is created wrapped around the code in the attribute, and that function needs to return the value that will prevent or allow the form submission.
So your original onsubmit attribute will be turned into:
function() {
checkPass();
}
which executes the checkPass function but discards its return value. By including the return in the attribute, it will be turned into:
function() {
return checkPass();
}
which will return the value returned to it by the checkPass function, thereby achieving the desired effect.

Related

JavaScript HTML validation function only works when the form elements are all filled

I'm making sign in form with submit. What I want to do is to alert when there is blank in the form. But the function only works when all of the form are filled. Here's the HTML and JS code. The result is the same using onsubmit inside of the HTML or addEventListener("submit" function name)
HTML : It's basically a form for sign in / ordering.
<form id="registration" method="POST" onsubmit="return validate();" action="phplink">
<p> <label for="custName">Name : </label>
<input type="text" id="cname" name="cname" required="required" /> </p>
</form>
JS :
function validate(event) {
event.preventDefault();
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}
The validation constrains, such as your required="required" are validated before your browser will trigger a submit event. If the validation fails (a value to a required field is not provided) it will not submit your form.
If you want to do the validation using JavaScript instead of the validation constraint attributes, you either need to remove the required="required" attribute (together with any other similar attributes) or you can add the novalidate attribute to your form to indicate that it should not perform this validation on submit.
If you use the latter, you can still use formElement.reportValidity() to see if all the elements satisfy their validation constraints.
If you add a required attribute to each field that shouldn’t be blank, it’ll prevent form submission with empty fields, like this...
<input type="text" name="username" required>
Hi you have several problem. on submit must pass event => onsubmit="return validate(event);" .
you must first defined result and thats your flag => var result = false .
if you want show alert then input dont need required attribute.
so this is your Fixed Code;
function validate(event) {
event.preventDefault();
var result = true;
var r = document.getElementById("registration");
var cname = r.cname.value;
var errMsg = "";
if (cname == "") {
errMsg += "Please enter your Name.\n";
}
if (errMsg.length != 0) {
alert(errMsg);
result = false;
}
return result;
}

Form submission validation with JavaScript

I am writing three functions in javascript to do different things. Search functions only needs firstname and lastname. Add and update functions needs everything to filled out completely. I have those working, however when submitting form, if anything is missing, it alerts me but still submits it. I don't want it to do that, how can i do it?
function search() {
checkme = false
//alert('all feilds must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
firstName = document.getElementById('firstName').value;
lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
}else{
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
}else{
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
return checkme;
}
, here is how i am calling the function as well
<input name="Action" type="submit" name="Search" value="Search" onclick="return search();"">
The reason your function fails to stop submission, is because of a system called event bubbling, where an event propagates up the DOM tree, and any handlers related to that event are triggered. There are also default events that occur on certain actions. Some of these are cancelable events, one of which is the Form Submit event. The e.preventDefault() command basically cancels the default action of the event, which is submitting the form, and prevents it from submitting regardless of the output of your function. We then call the submit() function manually when all requirements are satisfied.
Here's a version that I feel is shorter and easier to understand. No checkme variables needed either. It assumes your form has the id yourForm, and submits it if both first and last names pass the RegEx check.
function search(e) {
e.preventDefault();
const nameExpression = /^[a-zA-Z]+$/;
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const yourForm = document.getElementById('yourForm');
if (nameExpression.test(firstName) && nameExpression.test(lastName)) {
yourForm.submit();
} else {
alert('All fields must be filled out, and contain only alphabets');
}
}
document.getElementById('yourForm').addEventListener('submit', search);
<form id="yourForm">
<input type="text" id="firstName" placeholder="First Name" />
<br>
<input type="text" id="lastName" placeholder="Last Name" />
<br>
<input name="Action" type="submit" name="Search" value="Search">
</form>
P.S. You can do what you are trying to do here in pure HTML by adding the pattern attribute to your first and last name inputs. This also helps in case the user has an extension like NoScript installed, but the downside is you cannot control how the validation error looks.
(I'm beginner/intermediate in JS) I once also worked on something like this. I would suggest to add a paramater of 'e' in your function, en then writing "e.preventDefault" In your code. It would prevent the default submit action of your form. And then, you can submit the form in JS if it matches a certain condition, and if not, it will give you an alert.
Im guessing checkme, firstName and lastName weren't defined yet.
function search(e) {
e.preventDefault();
var checkme = false;
//alert('all fields must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
} else {
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
} else {
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
if (checkme == true) {
your_form.submit();
}
This may not be a perfect solution to your problem, but this is roughly how I do these things with JS and validating forms. I hope this helped.
Edit:
The code is the author's source code, I tried to not edit it too much.

How to Validate form without submitting it

I have a form that I want to validate before the form submits, when I press the Submit button. I know I am supposed to use preventDefault but I am not sure how to use it correctly:
function validateName() {
var name = form.firstname.value;
if (name == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else {
document.getElementById("firstnameInvalid").style.visibility = "hidden";
}
}
<form name="form" method="post" onsubmit="return validate(this)">
<p>First Name:
<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" />
<span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
</p>
You can stop the form by adding return statement to your validation code. onsubmit will stop the form submit when the function returns false.
your validate() must return a true or false value to it work with onsubmit="return validate(this)"
try something like
function validate(variable)
{
if(condition) //add a condition to validate
{
return false; //if condition are met, return false and do not submit
}
//you can create more than one condition following this logic.
return true; //if none of the conditions are met, he return true and submit
}
As others have said, returning false in your onsubmit callback will prevent the form from being submitted.
var form = document.getElementById( 'idgoeshere' );
form.onsubmit( function() {
// validate here
return false;
});

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

Javascript function fires twice on clicking 'Submit' button

I'm trying to insert records into DB using AJAX. I'm not sure why, but it seems the javascript function referenced in the onclick tag of the submit button gets fired twice, and hence I get two records in my DB per click.
Placing alerts in the JS, I have managed to figure out that the problem is in the JS function getting called twice, and not the PHP script making two inserts. So, I'm not posting the PHP script, unless asked.
Here's the HTML for the form:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}
You are calling processInfo twice once in submit handler and once in click handler. This might be the reason.
Here onclick="processInfo()" and inside
$("#notify").submit(function() {
processInfo();
return false;
});
processInfo() is called twice, both here, when the form submits:
$("#notify").submit(function() {
processInfo();
return false;
});
and here, when you click the submit button:
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
You should remove one of them.
You are calling the processInfo() function twice: once on the form submit event, and once on the onclick on the input.
You should only attach the processInfo() function on the submit event. Remove the onlick dom0 event handler (inline scripts are to be avoided).
Also, do not use return false; as it prevents event bubbling. Use ev.preventDefault() instead.
$("document").ready(function() {
$("#notify").submit(function(ev) {
ev.preventDefault();
processInfo();
});
});

Categories

Resources