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

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>

Related

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

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();">

Form validation error. Redirects to error page

so I've created a form. I'm trying to use JavaScript to validate fields. When I press submit, it does nothing. It just sends me to a page saying 'Your file was not found.' I do realize that the code is mostly HTML and not JS. I've been testing as I'm going and it's not working already. Any help is appreciated
Here is my code:
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
}
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
var lastname = document.myForm.lname.value;
if (lastname == "" || lastname == " ") {
alert("Last name is empty");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<title>My form validation</title>
</head>
<body>
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm()" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br>
Middle/Initial:
<input type="text" name="middle">
<br><br>
*Last Name:
<input type="text" name="lname">
<br><br>
*Email:
<input type="text" name="email">
<br><br>
Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br>
*Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
</body>
</html>
Add preventDefault() to the validateForm function & return true once the form is valid
function validateForm(e) {
e.preventDefault();
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middlename == "" || middlename == " ") {
alert("Middle name is empty");
return false;
}
}
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm(event)" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br> Middle/Initial:
<input type="text" name="middle">
<br><br> *Last Name:
<input type="text" name="lname">
<br><br> *Email:
<input type="text" name="email">
<br><br> Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br> *Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
Try attaching the handler in Javascript rather than inline-eval-HTML, and using preventDefault to prevent the default form submission.
<form name="myForm" action="fakeFormCheck.php" method="post">
and
document.querySelector('form[name="myForm"]').addEventListener('submit', (e) => {
// do tests
if (invalid) {
// something is invalid, prevent the default action of submitting the form:
e.preventDefault();
}
// else the form will submit by default
});
Use return in onsubmit="validateForm()" for example onsubmit="return validateForm()". second thing you are taking the middle name in middlename variable but your checking with some other varible if (middle == "" || middle == " ") {

JavaScript form validation (check for all letters only)

I'm trying to create one function that will check that a field is not blank, contains only letters and spaces. Validating that the field contains letters and spaces only does not appear to work as anything that's put in the field will return the alert message.
I'm trying to say:
If the name field is NOT letters and spaces then display this alert "...". Else return true.
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (x!==/^[A-Za-z ]+$/) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
else {
return true;
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
missing } at end of script and missing ; at else if
and use regex for check only letter and space
function validateForm() {
var regex = new RegExp("^[a-zA-Z ]+$");
var x = document.forms["newsletterForm"]["name"].value;
if (x == null || x == "") {
alert("Name must not be blank");
return false;
} else if (!regex.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)");
return false;
} else {
return true;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
Hi You can use regex for that
var regexExp = /^[a-zA-Z\s]*$/;
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
alert(x)
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (!regexExp.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
I'm thinking that the problem is your use of !==. !== would be looking for an absolute match between x and your regular expression object - that is, is x that regular expression object; not does it match that expression.
What about this:
else if (! /^[A-Za-z ]+$/.test(x))
use typeof
try
if(x == null || typeof x !== 'string')
{
//code here
}
An empty string isn't a valid value to check against.

My register form keeps refreshing the page

on my local server it works just fine but as soon as I take it live it starts only refershing the page instead of calling the validation.
This is my jquery:
<script>
$("form#registerform").submit(
function (e) {
e.preventDefault();
function validateForm() {
var RegisterUsername = document.forms["contactForm"]["RegisterUsername"].value;
var FirstName = document.forms["contactForm"]["FirstName"].value;
var LastName = document.forms["contactForm"]["LastName"].value;
var Email = document.forms["contactForm"]["Email"].value;
var RegisterPassword = document.forms["contactForm"]["RegisterPassword"].value;
if (RegisterUsername == null || RegisterUsername == "") {
$(".error-messages").text("Username required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (FirstName == null || FirstName == "") {
$(".error-messages").text("First name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
} else if (LastName == null || LastName == "") {
$(".error-messages").text("Last name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (Email == null || Email == "") {
$(".error-messages").text("Email required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (RegisterPassword == null || RegisterPassword == "") {
$(".error-messages").text("Password required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
}
}
</script>
This is my html:
<form id="registerform" name="contactForm" action="" onsubmit="return validateForm()" method="post">
<div class="pl-land-input">
<input class="email text-input" id="RegisterUsername" pattern=".{3,}" title="3 characters minimum" name="RegisterUsername" placeholder="Username" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" type="email" placeholder="Email" name="Email" id="Email">
</div>
<div class="pl-land-input">
<input class="email text-input" id="RegisterPassword" name="RegisterPassword" placeholder="Password" type="password">
</div>
<button type="submit" value="Submit" class="signup-plland">Sign up</button>
</form>
I have been trying to get my head around it and kept customizing it but I couldn't figure out the problem there was no problem in console for calling the Jquery libs.
I hope I can solve this asap.

HTML form validation issue

<script type="text/javascript">
function check(n,mail,msg)
{
if(name.toLowerCase()== "")
{
alert("Please Enter your name.");
document.getElementById("Name").select();
document.getElementById("Name").focus();
return false;
}
else if(lname.toLowerCase()== "")
{
alert("Please Enter your email.")
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if(ph == "")
{
alert("Please Enter your Contact Number.")
document.getElementById("message").focus();
return false;
}
return true;
}
=========================================================
<form method="post" name="contact_form" action="contact-form-handler.php">
<p> Your Name:
<input type="text" name="name"></p>
<p>Email Address:
<input type="text" name="email"></p>
<p>Message:
<textarea name="message"></textarea></p>
=========================================================
<input type="button" value="submit" onclick="return check(document.getElementById('name').value,document.getElementById('email').value,document.getElementById('message').value)" />
=========================================================
i am having issues with the HTML validation as when i clicked the button, there is no validation performed.
Instead .. add the validation on the form as below:
<form method="post" name="contact_form" action="contact-form-handler.php"
onsubmit="return validateForm()">
This works 100% times
try this instead for your button:
<input type="button" value="submit" onclick="function(){ check(document.getElementById('name').value,document.getElementById('email').value,document.getElementById('message').value)}" />
<form method="post" name="contact_form" action="contact-form-handler.php">
<p> Your Name:
<input type="text" id="name" name="name"></p>
<p>Email Address:
<input type="text" id="email" name="email"></p>
<p>Message:
<textarea id="message" name="message"></textarea></p>
Use this html markups. It has ids which you have missed.
You are using document.getElementById("name"). But the input field doesn't have id "name". Same for other fields.

Categories

Resources