HTML form automatically tries to validate and doesn't wait for the submit button to be clicked - javascript

I have this HTML form:
<form onclick="return validateForm();">
<h1 style="color:whitesmoke;">Register</h1>
<h2>Please enter your details:</h2>
<br />
<input type="email" name="email" placeholder="example#email.com" />
<input type="password" name="password" placeholder="Password" />
<br />
<input type="text" name="FirstName" placeholder="First name" />
<input type="text" name="LastName" placeholder="Last name" />
<br />
<div style="position:relative; top:10px;">
<label>Birth Date: <input type="date" id="birthday" name="DateOfBirth"></label>
</div>
<br />
<input type="number" placeholder="Age" min="10" max="120" name="age" style="width:15%;" />
<br />
<label style="position:relative; right:20px; top: 10px;">
Gender: <input id="setD_male" type="radio" name="gender" checked>
<label for="setD_male">Male</label>
<input id="setD_female" type="radio" name="gender">
<label for="setD_female">Female</label>
</label>
<br />
<div style="position:relative; top:10px;">
<input id="checkmark" type="checkbox" /><label> I agree to the terms and regulations.</label>
</div>
</div>
<br />
<input type="hidden" name="error" value="">
<button type="submit" id="Register" name="Register" class="submit-button">Register</button>
</form>
and this JavaScript:
var checkbox = document.getElementById("checkmark");
var button = document.getElementById("Register");
button.disabled = true;
checkbox.addEventListener("change", function () {
button.disabled = !checkbox.checked;
});
function validateForm() {
var error;
var email = document.getElementsByName("email")[0].value;
if (!email.endsWith(".com")) {
alert("Email has to end with '.com'");
return false;
}
var password = document.getElementsByName("password")[0].value;
var FirstName = document.getElementsByName("FirstName")[0].value;
var LastName = document.getElementsByName("LastName")[0].value;
var DateOfBirth = document.getElementsByName("DateOfBirth")[0].value;
var age = document.getElementsByName("age")[0].value;
var gender = document.getElementsByName("gender")[0].value;
if (
email === "" ||
password === "" ||
FirstName === "" ||
LastName === "" ||
DateOfBirth === "" ||
age === "" ||
gender === "" ||
email === null ||
password === null ||
FirstName === null ||
LastName === null ||
DateOfBirth === null ||
age === null ||
gender === null
) {
error = "nullRegistration";
window.location.href = "systemMessagesjsp.jsp?error=" + error;
return false;
}
if (
!Register(emailAddress, password, firstName, lastName, DOB, age, gender)
) {
error = "CantCreateUser";
window.location.href = "systemMessagesjsp.jsp?error=" + error;
return false;
} else {
alert("successfully signed in");
return true;
}
}
When I debug it, I can see that upon entering this page on my browser, the function "validateForm()" is being called, and also called again when I click the submit button. Why is it being called upon entering ?
I tried debugging it and I could see that upon entering the page, it jumps straight into validateForm and does all of the code inside of it, where instead, it should only perform the code inside of it if the user hits the submit button at the bottom of the page. I guess it registers the button from the previous stage as the submit button for some reason.

Use the submit event instead of the click event on the form.
<form onsubmit="return validateForm();">

Related

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

Single click to submit form

I'm having an issue when trying to submit my form. I have made a workaround so that the input gets sent to parse.com by using a hidden button which is visible until all fields are filled in, then this button is hidden and the real submit button is enabled. The problem is that I want to be able to submit the form directly by clicking the submit button without having to click the button twice. I have the following HTML:
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
Javascript:
<script type="text/javascript">
function getFullemail() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
e.preventDefault();
}else {
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
}
}
</script>
<script>
function functions() {
sendTheMail();
}
</script>
Parse.com script
$(document).ready(function() {
var parseAPPID = "bla";
var parseJSID = "bla";
Parse.initialize(parseAPPID, parseJSID);
var VcardObject = Parse.Object.extend("VcardObject");
$("#vcardForm").on("submit", function(e) {
e.preventDefault();
console.log("Handling the submit");
//add error handling here
//gather the form data
var data = {};
data.name = $("#name").val();
data.vorname = $("#vorname").val();
data.fullemail = $("#fullemail").val();
data.telefon = $("#telefon").val();
data.firma = $("#firma").val();
var vcard = new VcardObject();
vcard.save(data, {
success:function() {
openPage('danke');
console.log("Success");
},
error:function(e) {
console.dir(e);
}
});
});
});
If i understand you correctly, you'd like to click button after form is filed and if all fields are valid the form should be send. If so you need to do following changes:
1) remove from html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
2) change your validateForm - replace this lines
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
with
functions()
It will spare your from using two buttons.When submit button is clicked check if all the fields are filled in or not.Use && operator instead of || operator.Because you want all the fields to be filled
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' )
If all fields are filled it will alert a message which will tell you that your form is submitted.Otherwise it will alert you to fill all the fields
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' ) {
alert('form is sumbitted.');
e.preventDefault();
}else {
alert('fill all fields !!');
}
}
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="validateForm()" value=" submit " >
modify validateForm
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
return false
}
return true
}
and replace
console.log("Handling the submit");
//add error handling here
//gather the form data
with
if(!validateForm()) return
sendTheMail(...al your params here)
and the last step replace in your html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
with
<input type="submit" id="submitBtn" value=" ">

After Javascript Validation page redirect to another page

i have tryed to validate textbox using javascript.when i click on the submit button without inserting values to textbox it's display alert box.but after click on "ok" button , page redirect to payments.php page.how to fix it
<form method="post" action="payments.php" >
First Name : <br />
<input name="name" type="text" class="ed" id="name" /> <br />
E-mail : <br />
<input name="email" type="text" class="ed" id="email" /> <br />
<input name="but" type="submit" value="Confirm" onclick="Validation()" />
</form>
function Validation()
{
if (checkFName()&&checkemail())
{
window.event.returnValue = false;
}
}
function checkFName()
{
var tname = document.getElementById("name").value;
if((tname == null)||(tname == ""))
{
alert("Please Enter your First name");
return false;
}
return true;
}
function checkemail()
{
var email = document.getElementById("email").value;
var ap = email.indexOf("#");
var dp = email.lastIndexOf(".");
if((ap < 1)||(dp-ap < 1)||(dp >= email.length-1))
{
alert("invalid email address");
return false;
}
else
return true;
}
You need to change the CONFIRM button type to "button":
<input name="but" type="button" value="Confirm" onclick="Validation()" />
Give your form a name:
<form name="frm" method="post" action="payments.php">
then in your Validation() function, if your form passes validation, you can do the following:
function Validation()
{
if (checkFName()&&checkemail())
{
document.forms["frm"].submit();
}
}

Onclick Validation not working

I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, false);

Categories

Resources