How to Validate form without submitting it - javascript

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

Related

Form not submitting with single click

I have a form where I bound action with validation. Following is line of form which calls JavaScript check.
<form id="signup_form" method="post" action="javascript:check();">
I have following JavaScript:
function check(form){
flag = 0
doValidations();
if(flag==1){
return;
} else {
$('#signup_form').submit();
$('#signup_form').attr('action', 'NewSignupConfirm.php');
return false;
}
}
When I click on submit, it does all validation and even show message of else statement but do not submit form. Than I again click on submit button and it submits form. What is wrong with it? any suggestion.
<form id="signup_form" method="post" action="NewSignupConfirm.php" onsubmit="return check();">
function check(form){
flag = 0
doValidations();
if(flag==1){
return false;
} else {
return true;
}
}
You can try this below code
function check(form){
if(doValidations()){
return true;
} else {
return false;
}
}
You don't need to add flag variable just return true or false from doValidations method

Javascript - how to prevent form from sending with multiple validation checks?

It seems that you can prevent a form from sending if your validation check returns false.
I have:
<form name="registration" action="registration.php" onsubmit="return validate()">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
My validate() function in my javascript is made of multiple different checks though.
function validate() {
checkUsername();
checkPassword();
checkFirstname();
checkLastname();
checkBirthdate();
checkEmail();
checkPhone();
}
There might be a case where the user inputs valid data for all of them except one. If that's the case, how do I tell validate() to still send 'false' back to the form, so that it doesn't submit?
Edit: If anyone is still reading this, for some reason my form is still sending. I even changed my validate() function so the only statement is "return false;" Do I have a syntax error or something?
Edit2: I found another solution that is simple, even if a little archaic. It overcame an issue I had where the function was only evaluating the first check and returning.
function validate() {
var truth1 = checkUsername();
var truth2 = checkPassword();
var truth3 = checkFirstname();
var truth4 = checkLastname();
var truth5 = checkBirthdate();
var truth6 = checkEmail();
var truth7 = checkPhone();
return (truth1 && truth3 && truth5 && truth2 && truth4 && truth6 && truth7);
}
all your individual field validation functions should return a boolean.
then your overall form validation function will be
function validate() {
var checks = [
checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone,
].map(function(check) { return check(); });
return (checks.indexOf(false) === -1);
}
now ur validate function will return false if any field is invalid. true if all fields are valid
You can use Array.prototype.every() to call each function, if any function returns false, false will be returned from .every() call
<form name="registration" action="registration.php">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
function validate() {
return [checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone].every(function(check) {return check()});
}
document.querySelector("[name=registration]")
.onsubmit = function(event) {
event.preventDefault();
if (validate()) { this.submit() }
else { // notify user which fields are invalid }
}
The "validate" function needs to return a "true" boolean result only when ALL of the individual check functions return a "true" result.
One way to do this is to modify each line in the current "validate" function to something like the following code.
bUsernameSts = checkUsername();
if !bUsernameSts { return false };
...
<other checks>
...
return true;
The only way the new "validate" function can return "true" is if all of the individual input validation checks were successful.

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Attempting to prevent submitting empty form

I have a form in my HTML document, and it only has a "text" input, and a submit button.
I also have JavaScript that checks if the field is empty and returns true or false.
JSFiddle: http://jsfiddle.net/HBZ7t/
HTML:
<form onsubmit="checkNull();" method="post">
<input type="text" id="field">
<input type="submit">
</form>
JavaScript
function checkNull() {
var field = document.getElementById("field");
if(field.value !== "") {
return true;
}
return false;
}
However, the form can be submitted even if the text field is empty... Any suggestions?
You are doing nearly everything right, you just need to return the value from the function to the handler:
<form onsubmit="return checkNull();" method="post">
// -------------^^^^^^
In JavaScript you can use double exclamation points to check for lots of non-valid settings:
function checkNull() {
var field = document.getElementById("field");
if(!!field.value) {
return true;
} else {
return false;
};
FIDDLE
JS
var form=document.getElementById("form");
form.onsubmit=function(){
var field = document.getElementById("field");
if (field.value !== "") {
return true;
}
return false;
};
HTML
<form id="form" method="post">
<input type="text" id="field">
<input type="submit">
</form>
you can use event.preventDefault() to cancel a event, see mozila doc here
Also, check the very nice jQuery submit function and samples here
Check this sample: http://jsfiddle.net/HBZ7t/5/
$( "#target" ).submit(function( event ) {
if($('#field').val()=='')
{
alert('cancel event');
event.preventDefault();
}
});

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!

Categories

Resources