Form Validation using Javascript and PHP - javascript

Here is my code, I am having difficulties validating. Please tell me what I am doing wrong. I have everything listed that is required for my assignment, but I cannot understand where I am messing up. When I complete the registration and go to the next step it is here where I have problems. After making my selections on the Interests page, I am supposed to be able to hit register and get a notification thanking me for registering, but nothing happens... no next page or error is given. I didn't know what information to provide, so I have given all of my HTML, javascript, and php files. Thank you for any help and guidance you can provide as I am a student and very new to Javascript.
Registration.html and Registration.js:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript">
function formValidation() {
// Make quick references to our fields.
var username = document.getElementById('userName');
var password = document.getElementById('password');
var passwordv = document.getElementById('passwordVerify');
var firstname = document.getElementById('firstName');
var lastname = document.getElementById('lastName');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var signup = document.getElementById('signUpNewsletter');
// To check empty form fields.
if (username.value.length == 0) {
document.getElementById('head').innerText = "* All fields are required
*"; // This segment displays the validation rule for all fields
username.focus();
return false;
}
// Check each input in the order that it appears in the form.
if (textAlphanumeric(username, "* For your username please use alphabets
and numbers only *")) {
if (lengthDefine(password, 8, 16 )) {
if (matchPass(password,passwordv,"* Passwords do not match! *" )) {
if (inputAlphabet(firstname, "* For your name please use alphabets only
*")) {
if (inputAlphabet2(lastname, "* For your name please use alphabets only
*")) {
if (emailValidation(email, "* Please enter a valid email address *")) {
if (textAlphanumeric(phone, "* Enter phone number in format (xxx)xxx-xxxx
*")) {
}
}
}
}
}
}
return false;
}
// Function that checks whether input text is numeric or not.
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
} else {
document.getElementById('p6').innerText = alertMsg; // This segment
displays the validation rule for zip.
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or
not.
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p3').innerText = alertMsg; // This segment
displays the validation rule for name.
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or
not.
function inputAlphabet2(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p4').innerText = alertMsg; // This segment
displays the validation rule for name.
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text includes alphabetic and
numeric characters.
function textAlphanumeric(inputtext, alertMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p5').innerText = alertMsg; // This segment
displays the validation rule for address.
inputtext.focus();
return false;
}
}
// Function that checks whether the input characters are restricted
according to defined by user.
function lengthDefine(inputtext, min, max) {
var uInput = inputtext.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
document.getElementById('p1').innerText = "* Please enter between " + min
+ " and " + max + " characters *"; // This segment displays the
validation rule for username
inputtext.focus();
return false;
}
}
// Function that checks whether the 2 passwords are correct.
function matchPass(pass1,pass2, alertMsg) {
if (pass1.value === pass2.value) {
return true;
} else {
document.getElementById('p2').innerText = alertMsg; // This segment
displays the validation rule for username
pass2.focus();
return false;
}
}
// Function that checks whether an user entered valid email address or
not and displays alert message on wrong email address format.
function emailValidation(inputtext, alertMsg) {
var emailExp = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (inputtext.value.match(emailExp)) {
return true;
} else {
document.getElementById('p5').innerText = alertMsg; // This segment
displays the validation rule for email.
inputtext.focus();
return false;
}
}
// Function that checks whether an user entered valid phone number or not
and displays alert message on wrong phone address format.
function phoneValidation(inputtext, alertMsg) {
var phoneExp = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}
[0-9]{4}$/;
if (inputtext.value.match(phoneExp)) {
document.getElementById("regform").submit();
return true;
} else {
document.getElementById('p6').innerText = alertMsg; // This segment
displays the validation rule for email.
inputtext.focus();
return false;
}
}
}
</script>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="interests.html" id="regform" name="regform" >
<p id="head"></p>
<label for="userName">Username:</label>
<input type="text" name="userName" id="userName" placeholder="Enter your
Username" />
<p id="p1"></p>
<label for="Password">Password:
</label>
<input type="password" name="password" id="password" placeholder="Enter
your Password" />
<p id="p2"></p>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" id="passwordVerify"
placeholder="Enter in your Password again" />
<p id="p3"></p>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" id="firstName" placeholder="Enter
your First Name" />
<p id="p4"></p>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" id="lastName" placeholder="Enter your
Last Name" />
<p id="p5"></p>
<label for="email">Email:
</label>
<input type="text" name="email" id="email" placeholder="Enter your Email
Address" />
<p id="p6"></p>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="phone" id="phone" placeholder="Enter your Phone
Number" />
<p id="p7"></p>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter"
value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" id="signUpNewsletter"
value="No"> No
<input type="submit" value="Next step">
</form>
</section>
<!--<footer>This events site is for IT-FP3215 tasks.
</footer>-->
</body>
</html>
Interest.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Interests Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript" src="js/interest.js"></script>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="confirm.html" id="addform">
<input type="hidden" name="userName" id="userName" />
<input type="hidden" name="password" id="password" />
<input type="hidden" name="passwordVerify" id="passwordVerify" />
<input type="hidden" name="firstName" id="firstName" />
<input type="hidden" name="lastName" id="lastName" />
<input type="hidden" name="email" id="email" />
<input type="hidden" name="phone" id="phone" />
<input type="hidden" name="signUpNewsletter" id="signup" />
<label for="checkbox">Interests:
</label><br/>
<input type="checkbox" class="check1" id="check1" name="interests"
value="Swimming"> Swimming<br>
<input type="checkbox" name="interests" id="check2" class="check2"
value="Travelling"> Travelling <br>
<input type="checkbox" name="interests" id="check3" class="check3"
value="Reading"> Reading <br>
<label for="signUpNewsletter">Sign up for newsletter:
</label><br/>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter"
value="Yes" checked> Yes <br>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter"
value="No"> No<br>
<label for="comments">Comments:
</label><br/>
<textarea name="comments" id="comments" placeholder="Your Comments"
rows="10" cols="60"> </textarea><br>
<label for="referred">Referred by:
</label><br>
<input type="text" name="referred" id="referred" placeholder="Enter who
referred you" /><br>
<input type="button" value="Register" onclick="storeCookie()">
</form>
</section>
<footer>This events site is for IT-FP3215 tasks.
</footer>
</body>
</html>
Confirm.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Interests Page</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript" src="js/confirm.js"></script>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageFormContent">
Username: <p id="username">Placeholder</p>
Password: <p id="password">Placeholder</p>
First Name: <p id="firstName">Placeholder</p>
Last Name: <p id="lastName">Placeholder</p>
email: <p id="email">Placeholder</p>
Phone: <p id="phone">Placeholder</p>
Sign up News Letter: <p id="signup">Placeholder</p>
interest 1: <p id="username"></p>
Interest 2: <p id="username"></p>
Interest 3: <p id="username"></p>
Comments: <p id="phone">Placeholder</p>
<!--
Process content to display content on screen
-->
</section>
<footer>This events site is for IT-FP3215 tasks.
</footer>
</body>
</html>
PHP:
<?php
echo "You form is successfully submitted. Thank you for registering.";
?>
Validation.js:
//a function which splits the url into the different variabls
window.onload= function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');//split
the rul
for(var i in param_array){//save the parts in the arry
x = param_array[i].split('=');
params[x[0]] = x[1];
}
document.getElementById("userName").value = params.userName;//gets the
values of the username
document.getElementById("password").value = params.password;//gets
password value
document.getElementById("passwordVerify").value = params.passwordVerify;
document.getElementById("firstName").value = params.firstName;//first
name
document.getElementById("lastName").value = params.lastName;
document.getElementById("email").value = params.email;
document.getElementById("phone").value = params.phone;
document.getElementById("signup").value = params.signUpNewsletter;
}
function storeCookie(){
var username=document.getElementById("userName").value; //saves the
username in a variabe
document.cookie= "username=" + username; //saves the username variable in
a cookie
alert(document.cookie);
var password=document.getElementById("password").value; //saves the
password in a variable
document.cookie= "password=" + password; //saves the password varible in
a cookie
var fname=document.getElementById("firstName").value;//saves the first
name in a variable
document.cookie= "firstName=" + fname; //saves the firstname varible in a
cookie
var lname=document.getElementById("lastName").value ; //saves the last
name in a variable
document.cookie= "lastName=" + lname; //saves the lastnaem varible in a
cookie
var email=document.getElementById("email").value; //saves the email in a
variable
document.cookie= "email=" + email; //saves the email varible in a cookie
var phone=document.getElementById("phone").value ; //saves the phone in a
variable
document.cookie= "phone=" + phone;//saves the phone varible in a cookie
var signup=document.getElementById("signup").value; ////saves the sign up
value in a variable
document.cookie= "signUpNewsletter=" + signup;//saves the signup varible
in a cookie
var comments=document.getElementById("comments").value; //saves the
comments in a variable
document.cookie= "comments=" + comments; //saves the comments varible in
a cookie
var referred=document.getElementById("referred").value;//saves the
referred by value in a variable
document.cookie= "referred=" + referred; //saves the referred by varible
in a cookie
if(document.querySelector('.check1').checked){ //check if the checkbox is
checked if yes, it saves the value in cookie
var interest1=document.getElementById("check1").value;
document.cookie= "interest1=" + interest1;
}
if(document.querySelector('.check2').checked){ //check if the checkbox
is checked if yes, it saves the value in cookie
var interest2=document.getElementById("check2").value;
document.cookie= "interest2=" + interest2;
}
if(document.querySelector('.check3').checked){ //check if the checkbox
is checked if yes, it saves the value in cookie
var interest3=document.getElementById("check3").value;
document.cookie= "interest3=" + interest3;
}
document.getElementById("addform").submit();//submits the form
}

Found and solved problems:
registration.html:
Added the correct meta tags in head tags.
You must use overall the correct page name. I decided to use interests.html (not interest.html). So I changed the form tag to <form action="interests.html"...>.
I added onsubmit="return formValidation();" to the form tag, so that your form can be validated.
Error at line 9: "script" element between "head" and "body". I moved <script type="text/javascript">...</script> between the head tags.
Duplicate ID "signUpNewsletter" at <input type="radio" name="signUpNewsletter" id="signUpNewsletter" . You MUST NOT have duplicate id's. So I changed to "signUpNewsletter1" and "signUpNewsletter2".
Errors raised on "broken" lines. I corrected all errors by putting the corresponding value and/or comment on ONE LINE.
interests.html:
Added the correct meta tags in head tags.
Added <script type="text/javascript" src="js/validation.js"></script> into the head tags, so that you can access the functions in "validation.js". Otherwise you would have received an error.
I renamed <script src="js/interest.js" ...></script> to <script src="js/interests.js" ...></script>.
Error at line 8: "script" element between "head" and "body". I moved <script type="text/javascript" src="js/interest.js"></script> between the head tags.
Duplicate ID "signUpNewsletter" at <input type="radio" name="signUpNewsletter" id="signUpNewsletter" . You MUST NOT have duplicate id's. So I changed to "signUpNewsletter1" and "signUpNewsletter2".
Always close a js script with semicolon (";"). So I added one in onclick="storeCookie();".
Errors raised on "broken" lines. I corrected all errors by putting the corresponding value and/or comment on ONE LINE.
confirm.html:
Added the correct meta tags in head tags.
Error at line 9: "script" element between "head" and "body". I moved <script type="text/javascript" src="js/confirm.js"></script> between the head tags.
Duplicate ID "username" at interest 1: <p id="username"></p>. You MUST NOT have duplicate id's. So I changed to "interest1", "interest2" and "interest3".
Duplicate ID "phone" at Comments: <p id="phone">Placeholder</p>. It should be Comments: <p id="comments">Placeholder</p>, so I corrected it.
js/validation.js:
Errors raised on "broken" lines. I corrected all errors by putting the corresponding value and/or comment on ONE LINE.
Recommendations:
For avoiding a lot of errrors which I found in your code, you should start using a good IDE, which shows you were your code is error-prone and which can perfectly format your code. I personally use Netbeans 8.2 - choose to download the library for PHP (the 4th column in the download page). The newest version for PHP, e.g. version 9.0, will come on the market very soon (maybe in a couple of weeks). Note that the current released version 9.0 is only for java projects! So wait a bit further, until the new 9.0 library for PHP is released.
In order to achieve your functionality, you should use php pages instead of html pages. So that you can process the submitted form data, or the url, by php code, not by js code.
Whenever you run a page, open the "Console" or the "Inspector" from the corresponding "Development tools" menu of your browser. For example, in the Firefox browser, you can find "Console" and "Inspector" under the menu "Tools > Web Developer". With these tools you can see the eventual errors raised by your pages, or you can study the page structure. And many other cool things can be achieved with those tools.
Notes:
I did not change the text contents of your pages. I took just the proper steps to bring your code in a running, error-free state.
The pages (with the resolved codes):
All pages contain the working code. Just use them instead of yours.
registration.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript">
function formValidation() {
// Make quick references to our fields.
var username = document.getElementById('userName');
var password = document.getElementById('password');
var passwordv = document.getElementById('passwordVerify');
var firstname = document.getElementById('firstName');
var lastname = document.getElementById('lastName');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var signup = document.getElementById('signUpNewsletter');
// To check empty form fields.
if (username.value.length == 0) {
// This segment displays the validation rule for all fields
document.getElementById('head').innerText = "* All fields are required * ";
username.focus();
return false;
}
// Check each input in the order that it appears in the form.
if (textAlphanumeric(username, "* For your username please use alphabets and numbers only * ")) {
if (lengthDefine(password, 8, 16)) {
if (matchPass(password, passwordv, "* Passwords do not match! *")) {
if (inputAlphabet(firstname, "* For your name please use alphabets only * ")) {
if (inputAlphabet2(lastname, "* For your name please use alphabets only * ")) {
if (emailValidation(email, "* Please enter a valid email address *")) {
if (textAlphanumeric(phone, "* Enter phone number in format (xxx)xxx-xxxx * ")) {
return true;
}
}
}
}
}
}
}
return false;
}
// Function that checks whether input text is numeric or not.
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
} else {
// This segment displays the validation rule for zip.
document.getElementById('p6').innerText = alertMsg;
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or not.
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
// This segment displays the validation rule for name.
document.getElementById('p3').innerText = alertMsg;
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or not.
function inputAlphabet2(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
// This segment displays the validation rule for name.
document.getElementById('p4').innerText = alertMsg;
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text includes alphabetic and numeric characters.
function textAlphanumeric(inputtext, alertMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
// This segment displays the validation rule for address.
document.getElementById('p5').innerText = alertMsg;
inputtext.focus();
return false;
}
}
// Function that checks whether the input characters are restricted according to defined by user.
function lengthDefine(inputtext, min, max) {
var uInput = inputtext.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
// This segment displays the validation rule for username.
document.getElementById('p1').innerText = "* Please enter between " + min
+ " and " + max + " characters *";
inputtext.focus();
return false;
}
}
// Function that checks whether the 2 passwords are correct.
function matchPass(pass1, pass2, alertMsg) {
if (pass1.value === pass2.value) {
return true;
} else {
// This segment displays the validation rule for username.
document.getElementById('p2').innerText = alertMsg;
pass2.focus();
return false;
}
}
// Function that checks whether an user entered valid email address or not and displays alert message on wrong email address format.
function emailValidation(inputtext, alertMsg) {
var emailExp = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (inputtext.value.match(emailExp)) {
return true;
} else {
// This segment displays the validation rule for email.
document.getElementById('p5').innerText = alertMsg;
inputtext.focus();
return false;
}
}
// Function that checks whether an user entered valid phone number or not and displays alert message on wrong phone address format.
function phoneValidation(inputtext, alertMsg) {
var phoneExp = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1} [0 - 9]{4}$ /;
if (inputtext.value.match(phoneExp)) {
document.getElementById("regform").submit();
return true;
} else {
// This segment displays the validation rule for email.
document.getElementById('p6').innerText = alertMsg;
inputtext.focus();
return false;
}
}
</script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">
CapellaVolunteers<span class="dotcom">.org</span>
</a>
</div>
<nav>
<ul class="topnav">
<li>
Home
</li>
<li>
Invitation
</li>
<li>
Gallery
</li>
<li>
Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="interests.html" id="regform" name="regform" onsubmit="return formValidation();">
<p id="head"></p>
<label for="userName">Username:</label>
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<p id="p1"></p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter your Password" />
<p id="p2"></p>
<label for="passwordVerify">Verify your Password:</label>
<input type="password" name="passwordVerify" id="passwordVerify" placeholder="Enter in your Password again" />
<p id="p3"></p>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" placeholder="Enter your First Name" />
<p id="p4"></p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" placeholder="Enter your Last Name" />
<p id="p5"></p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder="Enter your Email Address" />
<p id="p6"></p>
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phone" id="phone" placeholder="Enter your Phone Number" />
<p id="p7"></p>
<label for="signUpNewsletter">Sign up for newsletter:</label>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter1" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" id="signUpNewsletter2" value="No"> No
<input type="submit" value="Next step">
</form>
</section>
<!--
<footer>
This events site is for IT-FP3215 tasks.
</footer>
-->
</body>
</html>
interests.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Interests Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript" src="js/interests.js"></script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">
CapellaVolunteers<span class="dotcom">.org</span>
</a>
</div>
<nav>
<ul class="topnav">
<li>
Home
</li>
<li>
Invitation
</li>
<li>
Gallery
</li>
<li>
Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="confirm.html" id="addform">
<input type="hidden" name="userName" id="userName" />
<input type="hidden" name="password" id="password" />
<input type="hidden" name="passwordVerify" id="passwordVerify" />
<input type="hidden" name="firstName" id="firstName" />
<input type="hidden" name="lastName" id="lastName" />
<input type="hidden" name="email" id="email" />
<input type="hidden" name="phone" id="phone" />
<input type="hidden" name="signUpNewsletter" id="signup" />
<label for="checkbox">Interests:</label><br/>
<input type="checkbox" name="interests" id="check1" class="check1" value="Swimming"> Swimming<br>
<input type="checkbox" name="interests" id="check2" class="check2" value="Travelling"> Travelling <br>
<input type="checkbox" name="interests" id="check3" class="check3" value="Reading"> Reading <br>
<label for="signUpNewsletter">Sign up for newsletter:</label><br/>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter1" value="Yes" checked> Yes <br>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter2" value="No"> No<br>
<label for="comments">Comments:</label><br/>
<textarea name="comments" id="comments" placeholder="Your Comments" rows="10" cols="60"> </textarea><br>
<label for="referred">Referred by:</label><br>
<input type="text" name="referred" id="referred" placeholder="Enter who referred you" /><br>
<input type="button" value="Register" onclick="storeCookie();">
</form>
</section>
<footer>
This events site is for IT-FP3215 tasks.
</footer>
</body>
</html>
confirm.html:
If you want to get the values posted from the interests.html, then you should maybe import the js/validation.js into confirm.html too. It's up to you.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Interests Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/confirm.js"></script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">
CapellaVolunteers<span class="dotcom">.org</span>
</a>
</div>
<nav>
<ul class="topnav">
<li>
Home
</li>
<li>
Invitation
</li>
<li>
Gallery
</li>
<li>
Registration
</li>
</ul>
</nav>
</header>
<section id="pageFormContent">
Username: <p id="username">Placeholder</p>
Password: <p id="password">Placeholder</p>
First Name: <p id="firstName">Placeholder</p>
Last Name: <p id="lastName">Placeholder</p>
email: <p id="email">Placeholder</p>
Phone: <p id="phone">Placeholder</p>
Sign up News Letter: <p id="signup">Placeholder</p>
interest 1: <p id="interest1"></p>
Interest 2: <p id="interest2"></p>
Interest 3: <p id="interest3"></p>
Comments: <p id="comments">Placeholder</p>
<!-- Process content to display content on screen -->
</section>
<footer>
This events site is for IT-FP3215 tasks.
</footer>
</body>
</html>
js/validation.js:
//a function which splits the url into the different variabls
window.onload = function () {
var params = {};
var param_array = window.location.href.split('?')[1].split('&'); //split the url
for (var i in param_array) {//save the parts in the array
x = param_array[i].split('=');
params[x[0]] = x[1];
}
document.getElementById("userName").value = params.userName;//gets the values of the username
document.getElementById("password").value = params.password;//gets password value
document.getElementById("passwordVerify").value = params.passwordVerify;
document.getElementById("firstName").value = params.firstName;//first name
document.getElementById("lastName").value = params.lastName;
document.getElementById("email").value = params.email;
document.getElementById("phone").value = params.phone;
document.getElementById("signup").value = params.signUpNewsletter;
};
function storeCookie() {
var username = document.getElementById("userName").value; //saves the username in a variabe
document.cookie = "username=" + username; //saves the username variable in a cookie
var password = document.getElementById("password").value; //saves the password in a variable
document.cookie = "password=" + password; //saves the password varible in a cookie
var fname = document.getElementById("firstName").value;//saves the first name in a variable
document.cookie = "firstName=" + fname; //saves the firstname varible in a cookie
var lname = document.getElementById("lastName").value; //saves the last name in a variable
document.cookie = "lastName=" + lname; //saves the lastnaem varible in a cookie
var email = document.getElementById("email").value; //saves the email in a variable
document.cookie = "email=" + email; //saves the email varible in a cookie
var phone = document.getElementById("phone").value; //saves the phone in a variable
document.cookie = "phone=" + phone;//saves the phone varible in a cookie
var signup = document.getElementById("signup").value; ////saves the sign up value in a variable
document.cookie = "signUpNewsletter=" + signup;//saves the signup varible in a cookie
var comments = document.getElementById("comments").value; //saves the comments in a variable
document.cookie = "comments=" + comments; //saves the comments varible in a cookie
var referred = document.getElementById("referred").value;//saves the referred by value in a variable
document.cookie = "referred=" + referred; //saves the referred by varible in a cookie
if (document.querySelector('.check1').checked) { //check if the checkbox is checked if yes, it saves the value in cookie
var interest1 = document.getElementById("check1").value;
document.cookie = "interest1=" + interest1;
}
if (document.querySelector('.check2').checked) { //check if the checkbox is checked if yes, it saves the value in cookie
var interest2 = document.getElementById("check2").value;
document.cookie = "interest2=" + interest2;
}
if (document.querySelector('.check3').checked) { //check if the checkbox is checked if yes, it saves the value in cookie
var interest3 = document.getElementById("check3").value;
document.cookie = "interest3=" + interest3;
}
document.getElementById("addform").submit();//submits the form
}
EDIT 1
Order of calling the pages:
The pages are made to be called in this way:
Load registration.html > Click on "Next step" button > Load interests.html > Click on "Register" button > Load confirm.html.
Project structure:
I can assure you that my codes are correct and tested. So, first, recheck the file names that you are using. They should be as presented in the file system structure below:
css
main.css
js
confirm.js
interests.js
validation.js
confirm.html
gallery.html
index.html
interests.html
invitation.html
registration.html
Activate cookies
In order to test the pages properly, you MUST clear the cookies (set by the code in js/validation.js) before each test. So, in Firefox, go to the menu "History > Clear Recent History..." and set:
Time range to clear: "Everything".
Check Cookies and Cache.
Then click the button "Clear Now".
Also, in order for the cookies to work, you have to set your browser to ACCEPT COOKIES. So, if you are using Firefox, follow these instructions. You should have these settings:
Accept cookies and site data from websites (recommended): checked.
Keep until: . I would select "Firefox is closed".
Accept third-party cookies and site data: "Always". Though "Never" is better, for testing your project set it to "Always".
And don't forget to check the "Console" and the "Inspector".
Although other things may prevent the pages from working, I hope the measures above will bring your project working.
EDIT 2
Problem found:
In the page registration.html, the formValidation() function was not returning true, even if all fields were valid. I changed the js script correspondingly now. Note that, earlier, all other functions resided in the formValidation() function. I brought them outside and changed the formValidation() so, that it works properly. Check registration.html again.
Note:
My tests were not taking into consideration how the validation function works, but only if the pages trigger the proper submits to the other pages without it. Then, in the end, I also tested if the function is triggered. When I saw that it's called properly, I stopped my tests. So it was my fault. I am sorry! Now I ran a complete test and it works. I hope it will work at your systems too.

Related

How to enable/disable a button dynamically with JavaScript, based on conditions with textfields

I have the following jsp page, consisting of 2 text fields, 2 password fields, 1 email field and 1 file-uploader, followed by a disabled button:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
My purpose is to enable and disable the button at run time using pure JavaScript, based on 2 conditions:
All the text fields, except the file-uploader, must all be filled in;
The password fields must match.
So I wrote the following JavaScript code:
RegScript.js
name = document.getElementById("name");
lastname = document.getElementById("lastname ");
email = document.getElementById("email");
password = document.getElementById("password");
confirmpassword = document.getElementById("confirmpassword");
register = document.getElementById("register");
//password matching & text fields checking
confirmpassword.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
password.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
The following script seems to work partially, but it has some errors: When I fill in all the text fields in order as they appear, in the moment that the passwords match the button is enabled, as well as if I delete the password it's disabled again, but if instead I delete one of the other three text fields (name, lastname or email) the button remains enabled, when it should not. What can I do to simplify the code (I'm not satisfied with the way I wrote my code, since it's redundant) and to solve to this issue?
You can DRY the validation logic in a validate function that runs whenever inputs change, which is set up using addEventListener on each of them.
This unifies the logic and makes it easy to extend later, for example you might check the emails .validity.valid property to see if it's an actual email.
This is a working snippet:
let name = document.getElementById("name");
let lastname = document.getElementById("lastname");
let email = document.getElementById("email");
let password = document.getElementById("password");
let confirmpassword = document.getElementById("confirmpassword");
let register = document.getElementById("register");
[name, lastname, email, password, confirmpassword].forEach(input => {
input.addEventListener("input", validate)
})
const hasLength = input => input.value.trim().length > 0;
function validate() {
let isValid =
hasLength(name) &&
hasLength(lastname) &&
hasLength(email) &&
hasLength(password) &&
password.value == confirmpassword.value;
console.log(isValid)
register.disabled = !isValid;
}
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>

Validating User Inputs Using Javascript

I am making a page that validates user inputs. The username should be in an email format and the password should be 7 or more characters. I think I have the code down, but am struggling to connect the javascript so that it works properly and validates the user inputs.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<br><br>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<br><br>
<button type="submit" class="signinbtn">Sign In</button>
</form>
function validateForm() {
let regexEmail = / ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (
password.length >= 7 || username.match(regexEmail)
) {
alert("Welcome");
return true;
}
else {
alert("error, username must be in email format & password must be 7 or more characters");
return false;
}
</body>
</html>
you are missing a bunch of script tags and the JS needs to be refactored with some minor changes.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
id="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
id="password"
required
/>
<br /><br />
<button type="submit" id="btn" class="signinbtn">Sign In</button>
</form>
<script type="text/javascript">
let regexEmail =
/ ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
document.getElementById("btn").addEventListener("click", (e) => {
e.preventDefault();
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
}
});
</script>
</body>
</html>
There's a couple of issues I can see here, first of all your JavaScript isn't within <script></script> tags.
Second, the validateForm function you have written isn't attached to your form HTML. Take a look here to see how you can run a function when your form is submitted:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Edit: Here's the list of issues:
Your form doesn't have an id attribute but you refer to myForm in your function
Your JavaScript needs to be wrapped in <script> tags
Your regex has spaces in which will prevent it from matching
You're missing a closing curly bracket at the end of your function
You're not attaching the function to your form so it won't be called when it is submitted (as per the link I posted).
Here's the fixed code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form id="myForm">
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
required
/>
<br /><br />
<button type="submit" class="signinbtn">Sign In</button>
</form>
<script>
function validateForm() {
let regexEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
return true;
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
return false;
}
}
const formEle = document.getElementById("myForm");
formEle.addEventListener("submit", validateForm);
</script>
</body>
</html>
Re:your comment - you have a function and you have an HTML form. In the original code, where is your function called? What triggers the validation on the form fields to be run? In the code I've provided I've attached your function to the submit event of the form so when the form is submitted, your function is called. There's other ways this could be handled - adding a click handler on the button, adding a change handler to the form fields, etc. etc.

How to show form validation errors in inputs NOT one by one in popups?

I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">

Why is my HTML file unable to use the JavaScript file that I have linked?

JavaScript file is not used in the HTML file despite linking it
I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.
<html>
<head>
<title>Registration Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/validation.js" type="text/javascript">
</script>
</head>
<body>
<form action="validate" method="post" name="register">
Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/> Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
required/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
function validateForm() {
//Use a regular expression to check for the pattern of the password
var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
var regexMobile = "^[0-9]{8}$";
var regexPost = "^[0-9]{6}$";
//Retrieve the VALUE from the "password" field found in the "register" form
var password1 = document.forms["register"]["password"].value;
var password2 = document.forms["register"]["cfpassword"].value;
var postalcode = document.forms["register"]["postal"].value;
if (matchPost === null) {
alert("The postal code given in the correct format. Please ensure
that is contains exactly 6 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
if (matchMobile === null) {
alert("The mobile number given in the correct format. Please ensure
that is contains exactly 8 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
return true
}
}
If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.

Function not activating upon onclick event

I have this script function but for some reason, it does not activate when i call the function on the onclick event on a button.
I want a javscript alert to pop up when i hit the submit button if either the first name text box or the last name text box has anything in there besides letters.
function CheckName(){
var NAME1 = getElementByID('FirstName').value;
var NAME2 = getElementByID('LastName').value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters))
{
alert('Your Details have been accepted.')
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
Below is the html:
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
</br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick= "CheckName()"">Submit </button>
</form>
use this html for your form
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
EDIT
this works, try it
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Styles.css">
<title>Patrick's Downtime Website</title>
</head>
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ > <br />
Last Name: <br />
<input type="text" id="LastName"> <br /> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
<script type = "text/javascript">
function CheckName(){
console.log(document);
var NAME1 = document.getElementById("FirstName").value;
var NAME2 = document.getElementById("LastName").value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters)) {
alert('Your Details have been accepted.')
} else {
alert('Please input alphanumeric characters only');
}
}
</script>
</body>
</html>
First, var NAME1 = getElementByID('FirstName').value; this is incorrect.
Function GetElementByID is a part of document and should be accessed using document.. Also, function's actual name is getElementById. So your line should be
var NAME1 = document.getElementById('FirstName').value;
Sample Fiddle
Second, if you wish to validate using regex, you should use .test function.
Sample fiddle
Few pointers,
Variable name with all caps is a convention for global variables. You should use lowercase. or camel-case variable names.
You can separate out validation logic to another function. This will allow you to put only submission related logic in Submit function.
Sample Fiddle
Reference
getElementById

Categories