Javascript form validation no alert on submit - javascript

I am trying to validate my form before submitting it but the form is being submitted anyway without any alerts coming up, even though the form is being submitted blank. When the submit button is clicked I want to make sure information has been completed and is correct, and when it is blank or incorrect an alert should come up without submitting the form.
Thanks
HTML
<!DOCTYPE html>
<html>
<head>
<title>Oaktown Football Club</title>
<meta charset="UTF-8">
<script src="formValidation.js"></script>
</head>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo"/>
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label><br>
<input type="text" size="35" name="fullName" id="name"><br>
<br><label>Email:</label><br>
<input type="text" size="35" name="email" id="email"><br>
<br><label>Phone:</label><br>
<input type="text" size="35" name="phone" id="phone"><br>
<br><label>Team:</label><br>
<select name="team"><br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select><br>
<br><label>I am:</label><br>
<select name="Member"><br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select><br>
<br><label>Comments:</label><br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea><br>
<br><input id="submit" type="submit" value="Submit"><br>
<br><input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
</html>
JavaScript
function formValidation()
{
var name = document.contactForm.fullName;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
}
{
return true;
}
}

It seems you had stored the value of the 'Full Name' in the variable 'name', but you were checking in your first 'if' block, you were checking if "fullName.value == ''".
Thus, a 'Reference Error' was being thrown.
After correcting it to if "name.value == ''", the code works fine.
Please find below the working code in JSBin :-
http://jsbin.com/kemokijucu/edit?html,js,console,output

You get name :
var name = document.contactForm.fullName;
But check by fullName :
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
Please up the code :)

You have made mistake in fetching & using name element from the form. Below is the correction in JS.
function formValidation() {
var fullName = document.contactForm.name;
var email = document.contactForm.email;
var phone = document.contactForm.phone;
var comment = document.contactForm.comment;
if (fullName.value == "") {
alert("Please enter your name!");
fullName.focus();
return false;
}
if (email.value == "") {
alert("Please enter your email address!");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
alert("Please enter a valid email address!");
email.focus();
return false;
}
if (phone.value == "") {
alert("Please enter your phone number!");
phone.focus();
return false;
}
if (phone.length < 2) {
alert("Please enter a valid phone number!");
phone.focus();
return false;
}
if (comments.value == "") {
alert("Please leave us a comment!");
comments.focus();
return false;
} {
return true;
}
}
<title>
Oaktown Football Club</title>
<body>
<header>
<img src="logo.png" alt="Oaktown Football Club Logo" />
<h1>Oaktown Football Club</h1>
<nav>
Homepage
Competitions
Contact
</nav>
</header>
<section>
<h2>Contact Us</h2>
<article>
<h3>Secretary</h3>
<p>Name: Laci Tanner</p>
<p>Phone: (02) 6620 3324</p>
<p>Email: secretary#oaktownfa.com.au</p>
<h3>Leave us a message</h3>
<form method="post" action="actionPage.html" name="contactForm" onsubmit="return formValidation();">
<label>Full Name:</label>
<br>
<input type="text" size="35" name="fullName" id="name">
<br>
<br>
<label>Email:</label>
<br>
<input type="text" size="35" name="email" id="email">
<br>
<br>
<label>Phone:</label>
<br>
<input type="text" size="35" name="phone" id="phone">
<br>
<br>
<label>Team:</label>
<br>
<select name="team">
<br>
<option>Please Choose</option>
<option>Adults</option>
<option>Under 12s</option>
<option>Under 6s</option>
</select>
<br>
<br>
<label>I am:</label>
<br>
<select name="Member">
<br>
<option>Please Choose</option>
<option>Thinking about joining the club</option>
<option>Already a club member</option>
</select>
<br>
<br>
<label>Comments:</label>
<br>
<textarea id="comments" type="text" rows="5" cols="75"></textarea>
<br>
<br>
<input id="submit" type="submit" value="Submit">
<br>
<br>
<input type="reset">
</form>
</article>
</section>
<footer>
<p>Copyright - Oaktown Football Club</p>
</footer>
</body>
Do try and debug the same using console in the browser.
You can change the type attribute of email field to email for auto email validation on the field.

Related

Disable Submit button until all form fields are validated

I have a function to validate all fields, but I also want to disable the submit button until the fields are filled out AND validation is complete. What is the best way to go about doing this? I'm very new to JavaScript so very specific instructions/explanation is appreciated :)
function fieldValidation() {
var name = document.forms['RegForm']['Name'].value;
var address = document.forms['RegForm']['Address'].value;
var email = document.forms['RegForm']['EMail'].value;
var password = document.forms['RegForm']['Password'].value;
var telephone = document.forms['RegForm']['Telephone'].value;
var job = document.forms['RegForm']['Job'].value;
var comment = document.forms['RegForm']['Comment'].value;
var fullName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var phnFormat = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
if (name === '') {
alert('Please enter your name.');
return false;
}
if (!fullName.test(name)) {
alert('Please make sure we have your full name.');
return false;
}
if (address === '') {
alert('Please enter your address.');
return false;
}
if (email === '') {
alert('Please enter your e-mail address.');
return false;
}
if (password === '') {
alert('Please enter a password.');
return false;
}
if (telephone === '') {
alert('Please enter your telephone number.');
return false;
}
if (!phnFormat.test(telephone)) {
alert('Please enter your phone number in the following format: (123) 555-1212)');
return false;
}
if (job.value === '') {
alert('Please select a job choice.');
return false;
}
if (comment.value === '') {
alert('Please enter a comment.');
return false;
}
return true;
}
<div class="container">
<main>
<form name="RegForm" action="/submit.php" onsubmit="return fieldValidation()" method="post">
<p>Name: <input type="text" size=65 name="Name" id="nameInput"> </p><br>
<p>Address: <input type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input type="email" size=65 name="EMail"> </p>
<input type="checkbox" id="confirmApp" name="confirm">
<label for="confirmApp">I want to receive an email confirming my application.</label>
<br>
<p>Password: <input type="password" size=65 name="Password"> </p><br>
<p>Telephone: <input type="tel" size=65 name="Telephone"> </p><br>
<label for="jobChoice">Job Choice:</label>
<select name="Job" id="jobChoice">
<option value="">--- Select Job Choice ---</option>
<option value="IT">IT</option>
<option value="Human Resources">Human Resources</option>
<option value="Maintenance">Maintenance</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select></p><br><br>
<p>Comments: <textarea cols="100" rows="10" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" id="submitBtn">
<input type="reset" value="Reset" name="Reset"></p>
</form>
</main>
</div>
You could do it in a couple of ways:
You could have a onclick="your validation function" for each input running your validation code.
Or you could add the required tag to each required input, this way the user cant submit the form unless every required field is filled in a.e. <input type="text" size="65" name="Name" id="nameInput"required>, however option two does not hide the submit button.
If you only want to disable the submission and not the submit button persé I'd suggest using the required tag for the relevant input fields.

How to get alert boxes and validation working on this code

I got this code made but i can't get it to validate the required fields with alert boxes for missing fields or submit to a pop up window like i'm trying to do. The code is supposed to validate certain fields that only show up when one of the radio buttons are clicked and a pop up window containing a url is supposed to show up after submission. Not working. Need help.
Code:
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
if(document.getElementById('businessCheck').checked) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var address=document.forms["myForm"]["address"];
var bname=document.forms["myForm"]["bname"];
var url=document.forms["myForm"]["url"];
var id=document.forms["myForm"]["tax"];
var rname=document.forms["myForm"]["rname"];
var email=documen.forms["myForm"]["email"];
if(address.value == "") {
alert("Please enter an address.");
address.focus;
return false;
}
if(bname.value == "") {
alert("Please enter a business name.");
bname.focus;
return false;
}
if(url.value == "") {
alert("Please enter a business URL.");
url.focus;
return false;
}
if(id.value == "") {
alert("Please enter a business tax ID.");
id.focus;
return false;
}
if(rname.value == "") {
alert("Please enter a residence name.");
rname.focus;
return false;
}
if(email.value == "") {
alert("Please enter an email address.");
email.focus;
return false;
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<center><h1>Fill the form below</h1>
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<center><p><b>Address: </b><input type="text" name="address"></p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business <input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence<br>
<div id="ifBusiness" style="display:none">
<b>Business Name: </b><input type="text" id="name" name="bname"><br>
<b>Business Website URL: </b><input type="text" id="url" name="url"><br>
<b>Business Tax ID: </b><input type="text" id="tax" name="tax"><br>
<input type="submit" value="Submit">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b><input type="text" id="name" name="rname"><br>
<b>Email: </b><input type="text" id="email" name="email"><br>
<input type="submit" value="Submit"></center>
</div>
</form>
<hr>
<hr>
</body>
</html>
The alert boxes are not popping up and I'm not sure how to fix it.
As per the comments, I have added the if-clause checking for business or not.
I also added the code to open the form submission into a new window.
Finally I cleaned up all the things you should not use anymore, like obsolete HTML tags like <b> and <center> and such, adding comments when appropriate.
<!DOCTYPE html>
<html>
<head>
<title>
<h1>Javascript Assignment</h1>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h2>Fill the form below</h2>
</title>
<!-- center tag is deprecated and should be replaced by CSS -->
<style>
head {
text-align: center;
}
.bold {
font-weight: bold;
}
</style>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<span class="bold">Address: </span>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<span class="bold">Name: </span>
<input type="text" id="name" name="rname">
<br>
<span class="bold">Email: </span>
<input type="text" id="email" name="email">
</div>
<!-- missed the closing </div> -->
</div>
</div>
<!-- Only one submit button per form -->
<input type="submit" value="Submit">
</form>
<hr>
<hr>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
<!-- both scripts can be in the same <script> tag -->
<script>
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if ( is_business ) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if ( address.value == "" ) {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the banem, tax and url if a business is selected
if ( is_business ) {
if ( bname.value == "" ) {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
// It does not make sense to call the tax id "id", tax is a better name.
if ( tax.value == "" ) {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if ( url.value == "" ) {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if ( rname.value == "" ) {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if ( email.value == "" ) {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open( '', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234' );
// Set the form target to the name of the newly created popup.
var form = document.querySelector( 'form[name="myForm"]' );
form.setAttribute( 'target', 'SELU' );
// Continue as normal
return true;
}
</script>
</body>
</html>

On submission, this form will not run the validation script

I have tried and tried and cannot figure out why when I submit this form it will not activate the javascript function Validate().
This is nearly an exact replica of another form with namely one change: I've added a textarea and removed some check boxes.
I could really use some help troubleshooting this thing...
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate()">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
function Validate() {
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
There is an exception at the line of code
document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == ""
Dont have any name a7aa41d9-b309-48d7-af97-5a2ce65eb850_First in your document, so that the [0] is undefined.
If you change from
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
to
if (document.getElementsByName('be9953c9-471c-42f4-a1cf-524f5b67fc38_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
The message Please fill out your first name will shown.
You need to prevent the default behavior using e.preventDefault(); otherwise it will try to submit the form
function Validate(e) {
e.preventDefault();
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate(event)">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button type='submit' id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>

Basic HTML-Javascript based form validation

I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.

print out div in JavaScript if return false

index.php
<body align="center">
<form action="index2.php" method="post" onsubmit="return ValidateEmail()">
<div class="container">
<h1> TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
JavaScript
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
// alert("Invalid email address.");
return false;
!-- print out div that show this alert text-->
}
else {
return true;
!-- else return true dont submit the post-->
}
}
</script>
my intention is when the user dont enter or enter wrong email , it will pop a text or a box in html div and telling them they didt entering the right email , how i going to make javasctrip print out a div your email is invalid ?? if return true submit post else not posted. and i dont wanted to use jquery. thank you
Add A Div for pop text like this
<div id="emailMessage"></div>
Then replace your JavaScript code with this
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("emailMessage").innerHTML = "Invalid email address.";
//alert("Invalid email address.");
return false;
} else {
document.getElementById("emailMessage").innerHTML = "";
return true;
}
}
You must create an error message in <div> with the attribute hidden.
<div id="errorMessage" hidden>
Error message here...
</div>
The hidden attribute makes the element to be hidden.
If the user enters invalid email, you can set the hidden of that div error message to false.
document.getElementById("errorMessage").hidden=false;
Place that code after/before the return false; of your javascript.
An easier alternative would be to use the HTML5 validation of the email input as suggested in this SO-thread: HTML5 Email Validation.
Just use input type email and the validation will be handled by the browser:
<form>
<input type="email" placeholder="Enter your email">
<input type="submit" value="Submit">
</form>
You can reffer the foolowing sample code
used "" to dispaly the error message.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function IsValidEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
function myFunction() {
var email = document.getElementById("Useremail").value;
if (!IsValidEmail(email)) {
document.getElementById("errorMsg").innerHTML = "Invalid email address.";
window.stop();
return false;
<!-- print out div that show this alert text-->
}
else {
document.getElementById("errorMsg").innerHTML = "";
return true;
<!-- else return true dont submit the post-->
}
}
</script>
<form method="post" action="index2.php" onsubmit="return myFunction()" >
<div class="container">
<h1> AUG SWIFT TEST </h1>
<br>
<label>LOG IN WITH FACEBOOK</label>
<br>
<br>
<label>CHANGE FACEBOOK ACCOUNT</label>
<br>
<br>
<label><input id="Username" type="text" placeholder="name" name="name" maxlength="30"/></label>
<br>
<br>
<label><input id="Useremail" type="text" placeholder="email" name="email"/></label><div id="errorMsg"></div>
<br>
<br>
<label>
<select name="gender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</label>
<br>
<br>
<input type="submit" onClick="myFunction()" name="submit" value="Sign Up"/>
</form><!--end of form -->
</body>
</html>

Categories