issue in my jquery form validation - javascript

Issue in my jquery form validations.
here four fields USERNAME,EMAIL,PASSWORD,CONFIRM PASSWORD. But the first two field will be validated the third field will not be validated. I dont know what the reason.?
Code shows below...
$(document).ready(function() {
$('#signup').click(function(){
if(validateSignUpForm()) alert('valid form');
else alert('validation error');
});
});
function IsEmail() {
var emails=document.forms["signUpForm"]["email"].value;
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var valid= regex.test(emails);
if(!valid){
alert("Email not valid..");
return false;
} else {
return true;
}
}
function validateSignUpForm() {
var isValid = true;
var errorMessage = '';
var username = $('#username').val();
var email = $('#email1').val();
var pass1 = $('#password1').val();
var pass2 = $('#confirmpass1').val();
if(!username) {
isValid = false;
errorMessage += ' \n * Please enter a user name.';
}
if(!email) {
isValid = false;
errorMessage += ' \n * Please enter your email.';
}
else {
return IsEmail();
}
if(!pass1){
isValid = false;
errorMessage += ' \n * Please enter your password..';
}
if(!isValid) {
alert('You have some validation errors. Please fix the following errors to continue.'+errorMessage);
}
return isValid;
}
</script>
</head>
<body>
<div id="wrapper">
<div id="titlebar">
<img src="img/title.PNG" width="300px" height="25px"/>
<form method="post" name="signUpForm" id="signUp" >
</div>
<div id="username_cont">
<!-- <img src="img/username.PNG" width="250px" height="30px"/>-->
<input type="text" class="inputpassword" placeholder="username" name="username" id="username"/>
</div>
<div id="email">
<input type="email" class="inputpassword" placeholder="email" name="email" id="email1"/>
</div>
<div id="password">
<input type="password" class="inputpassword" placeholder="password" name="password" id="password1"/>
</div>
<div id="confirmpwd">
<input type="password" class="inputpassword" placeholder="confirm password" name="confirmpassword" id="confirmpass1" onkeyup="return checkPass(); return false;"/>
</div>
<div id="signupConfirm">
<button type="button" name="submit" id="signup">
<img src="img/signUPlogin.PNG" width="230px" height="30px">
</button>
</div>
</form>
</div>
</body>

This code block:
if (!email) {
isValid = false;
errorMessage += ' \n * Please enter your email.';
}
else {
return IsEmail();
}
If e-mail is invalid you set isValid to false and update validation message but if it's valid you simply return and code after that won't be executed. Just change it to:
if (!iIsEmail()) {
isValid = false;
errorMessage += ' \n * Please enter your email.';
}
Moreover your IsEMail() function will read value from <div>, not from <input>. Change it to:
function IsEmail(emails) {
// Remove this line:
// var emails=document.forms["signUpForm"]["email"].value;
...
}
It'll be used like this:
if (!iIsEmail(email)) {
isValid = false;
errorMessage += ' \n * Please enter your email.';
}
Moreover note that you're not checking if password and confirmed password are equal. To put all together your validation code will be (something like):
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
function validateSignUpForm() {
var isValid = true;
var errorMessage = '';
var username = $('#username').val();
var email = $('#email1').val();
var pass1 = $('#password1').val();
var pass2 = $('#confirmpass1').val();
if (!username) {
isValid = false;
errorMessage += ' \n * Please enter a user name.';
}
if (IsEmail(email)) {
isValid = false;
errorMessage += ' \n * Please enter your email.';
}
if (!pass1) {
isValid = false;
errorMessage += ' \n * Please enter your password..';
}
if (!pass2) {
isValid = false;
errorMessage += ' \n * Please confirm your password..';
}
if (pass1 != pass2) {
isValid = false;
errorMessage += ' \n * Password and confirmation must match.';
}
if (!isValid) {
alert('You have some validation errors. Please fix the following errors to continue.'+errorMessage);
}
return isValid;
}

Related

How can I prevent my form from being submitted?

I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.

Warning messages for form validation fields are not occurring

I have created my code accordingly.
I recently changed the form action and now the form validation warnings are no longer applying on page load. For instance, if I click submit without entering data into any of the fields, I get 0 response and forwarded to the confirm.html page which should not be happening.
window.onload = init;
//creation of checkRegistration method
function checkRegistration() {
//definition of variables
//var checkev = 0;
var userName = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var passwordVerify = document.getElementById('passwordVerify').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var phoneNumber = document.getElementById('phoneNumber').value;
var signUpNewsletter = document.getElementById('signUpNewsletter').value;
var userNameError = false,
passwordError = false,
passwordVerifyError = false,
firstNameError = false,
lastNameError = false,
emailError = false,
phoneNumberError = false;
// define logic checks
var alphaOnly = /^[A-Za-z]+$/;
var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
var atrate = email.indexOf("#");
var dot = email.lastIndexOf(".");
//clearning out warniings
document.getElementById('userNameWarning').innerHTML = "";
document.getElementById('passwordWarning').innerHTML = "";
document.getElementById('passwordVerifyWarning').innerHTML = "";
document.getElementById('firstNameWarning').innerHTML = "";
document.getElementById('lastNameWarning').innerHTML = "";
document.getElementById('emailWarning').innerHTML = "";
document.getElementById('phoneNumberWarning').innerHTML = "";
//validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
if (userName == "") {
//passes error requiring something to be entered
document.getElementById('userNameWarning').innerHTML = "A username is required.";
//moves cursor to this field if error occurs
//document.pageForm.userName.focus();
//document.pageForm.userName.select();
//checkev=0;
userNameError = true;
//ensures that username meets alphanumberic regex requirements
} else if (!userName.match(alphaNum)) {
document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
userNameError = true;
//passes check with no error and increments checkev
//else {
// document.getElementById('userName').innerHTML = "";
//checkev++;
}
//validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
if (password == "") {
//passes error requiring something to be entered
document.getElementById('passwordWarning').innerHTML = "A password is required.";
//moves cursor to this field if error occurs
//document.pageForm.password.focus();
//document.pageForm.password.select();
//checkev = 0;
passwordError = true;
//check if password length is 8 or more characters
} else if (password.length <= 8) {
document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
passwordError = true;
//else {
//document.getElementById('password').innerHTML = "";
//checkev++;
}
//validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
if (passwordVerify == "" ) {
document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
//document.pageForm.passwordVerify.focus();
//document.pageForm.passwordVerify.select();
//checkev = 0;
passwordVerifyError = true;
} else if (password != passwordVerify) {
document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
passwordVerifyError = true;
//else {
//document.getElementById('passwordVerify').innerHTML = "";
// checkev++;
}
//validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
if (firstName == "") {
document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
//document.pageForm.firstName.focus();
//document.pageForm.firstName.select();
//checkev = 0;
firstNameError = true;
} else if (!(firstName.match(alphaOnly))) {
document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
firstNameError = true;
//else {
//document.getElementById('firstName').innerHTML = "";
//checkev++;
}
//validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
if (lastName == "") {
document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
//document.pageForm.lastName.focus();
//document.pageForm.lastName.select();
// checkev = 0;
lastNameError = true;
} else if (!(lastName.match(alphaOnly))) {
document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
lastNameError = true;
//else {
// document.getElementById('lastName').innerHTML = "";
//checkev++;
}
//validation of email
if (email == "") {
document.getElementById('emailWarning').innerHTML = "Your email address is required.";
// document.pageForm.email.focus();
// document.pageForm.email.select();
//checkev = 0;
emailError = true;
} else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
emailError = true;
// else {
// document.getElementById('email').innerHTML = "";
//checkev++;
}
//validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
if (phoneNumber == "") {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
//document.pageForm.phoneNumber.focus();
//document.pageForm.phoneNumber.select();
//checkev = 0;
phoneNumberError = true;
} else if (!(phoneNumber.match(phoneFormat))) {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
// else {
//document.getElementById('phoneNumber').innerHTML = "";
// checkev++;
phoneNumberError = true;
}
if (userNameError === true) {
document.getElementById('userName').focus();
return false;
} else if (passwordError === true) {
document.getElementById('password').focus();
return false;
} else if (passwordVerifyError === true) {
document.getElementById('passwordVerify').focus();
return false;
} else if (firstNameError === true) {
document.getElementById('firstName').focus();
return false;
} else if (lastNameError === true) {
document.getElementById('lastName').focus();
return false;
} else if (emailError === true) {
document.getElementById('email').focus();
return false;
} else if (phoneNumberError === true) {
document.getElementById('phoneNumber').focus();
return false;
}
//validation of sign up for newsletter, checking to see if there is nothing
}
<form id="pageForm">
<form action="/registration.html" onsubmit=checkRegistration() method="get">
<label for="userName">Username:</label><label2 id="userNameWarning"></label2>
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<!--<span class="error" id="userName"></span><br><br>-->
<label for="Password">Password:
</label><label2 id="passwordWarning"></label2>
<input type="password" name="password" placeholder="Enter your Password" />
<!--<span class="error" id="password"></span><br><br>-->
<label for="passwordVerify">Verify your Password:
</label><label2 id="passwordVerifyWarning"></label2>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<!--<span class="error" id="passwordVerify"></span><br><br>-->
<label for="firstName">First Name:
</label><label2 id="firstNameWarning"></label2>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<!--<span class="error" id="firstName"></span><br><br>-->
<label for="hostName">Last Name:
</label><label2 id="lastNameWarning"></label2>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<!--<span class="error" id="lastName"></span><br><br>-->
<label for="email">Email:
</label><label2 id="emailWarning"></label2>
<input type="text" name="email" placeholder="Enter your Email Address" />
<!--<span class="error" id="email"></span><br><br>-->
<label for="phoneNumber">Phone Number:
</label><label2 id="phoneNumberWarning"></label2>
<input type="text" name="phoneNumber" placeholder="Enter your Phone Number" />
<!--<span class="error" id="phoneNumber"></span><br><br>-->
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked > Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
<!-- Creation of submit button-->
<input type="submit" value="Submit" formaction=confirm.html>
</form></form></body>
First, you need to remove window.onload = init; as it throws an error initially.
Second, your form tag is nested in another form tag which is completely unnecessary and prevents the form from triggering the onsubmit function which causes the error of submitted empty forms.
Lastly, your input elements don't actually have IDs, just names. So as Alon said in the comments your document.getElementById('element').value wont function correctly.
Try moving forward with the code snippet below as it corrects some of the main errors so you're actually hitting the validation conditions.
//creation of checkRegistration method
function checkRegistration() {
//definition of variables
//var checkev = 0;
var userName = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var passwordVerify = document.getElementById('passwordVerify').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var phoneNumber = document.getElementById('phoneNumber').value;
var signUpNewsletter = document.getElementById('signUpNewsletter').value;
var userNameError = false,
passwordError = false,
passwordVerifyError = false,
firstNameError = false,
lastNameError = false,
emailError = false,
phoneNumberError = false;
// define logic checks
var alphaOnly = /^[A-Za-z]+$/;
var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
var atrate = email.indexOf("#");
var dot = email.lastIndexOf(".");
//clearning out warniings
document.getElementById('userNameWarning').innerHTML = "";
document.getElementById('passwordWarning').innerHTML = "";
document.getElementById('passwordVerifyWarning').innerHTML = "";
document.getElementById('firstNameWarning').innerHTML = "";
document.getElementById('lastNameWarning').innerHTML = "";
document.getElementById('emailWarning').innerHTML = "";
document.getElementById('phoneNumberWarning').innerHTML = "";
//validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
if (userName == "") {
//passes error requiring something to be entered
document.getElementById('userNameWarning').innerHTML = "A username is required.";
//moves cursor to this field if error occurs
//document.pageForm.userName.focus();
//document.pageForm.userName.select();
//checkev=0;
userNameError = true;
//ensures that username meets alphanumberic regex requirements
} else if (!userName.match(alphaNum)) {
document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
userNameError = true;
//passes check with no error and increments checkev
//else {
// document.getElementById('userName').innerHTML = "";
//checkev++;
}
//validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
if (password == "") {
//passes error requiring something to be entered
document.getElementById('passwordWarning').innerHTML = "A password is required.";
//moves cursor to this field if error occurs
//document.pageForm.password.focus();
//document.pageForm.password.select();
//checkev = 0;
passwordError = true;
//check if password length is 8 or more characters
} else if (password.length <= 8) {
document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
passwordError = true;
//else {
//document.getElementById('password').innerHTML = "";
//checkev++;
}
//validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
if (passwordVerify == "" ) {
document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
//document.pageForm.passwordVerify.focus();
//document.pageForm.passwordVerify.select();
//checkev = 0;
passwordVerifyError = true;
} else if (password != passwordVerify) {
document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
passwordVerifyError = true;
//else {
//document.getElementById('passwordVerify').innerHTML = "";
// checkev++;
}
//validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
if (firstName == "") {
document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
//document.pageForm.firstName.focus();
//document.pageForm.firstName.select();
//checkev = 0;
firstNameError = true;
} else if (!(firstName.match(alphaOnly))) {
document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
firstNameError = true;
//else {
//document.getElementById('firstName').innerHTML = "";
//checkev++;
}
//validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
if (lastName == "") {
document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
//document.pageForm.lastName.focus();
//document.pageForm.lastName.select();
// checkev = 0;
lastNameError = true;
} else if (!(lastName.match(alphaOnly))) {
document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
lastNameError = true;
//else {
// document.getElementById('lastName').innerHTML = "";
//checkev++;
}
//validation of email
if (email == "") {
document.getElementById('emailWarning').innerHTML = "Your email address is required.";
// document.pageForm.email.focus();
// document.pageForm.email.select();
//checkev = 0;
emailError = true;
} else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
emailError = true;
// else {
// document.getElementById('email').innerHTML = "";
//checkev++;
}
//validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
if (phoneNumber == "") {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
//document.pageForm.phoneNumber.focus();
//document.pageForm.phoneNumber.select();
//checkev = 0;
phoneNumberError = true;
} else if (!(phoneNumber.match(phoneFormat))) {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
// else {
//document.getElementById('phoneNumber').innerHTML = "";
// checkev++;
phoneNumberError = true;
}
if (userNameError === true) {
document.getElementById('userName').focus();
return false;
} else if (passwordError === true) {
document.getElementById('password').focus();
return false;
} else if (passwordVerifyError === true) {
document.getElementById('passwordVerify').focus();
return false;
} else if (firstNameError === true) {
document.getElementById('firstName').focus();
return false;
} else if (lastNameError === true) {
document.getElementById('lastName').focus();
return false;
} else if (emailError === true) {
document.getElementById('email').focus();
return false;
} else if (phoneNumberError === true) {
document.getElementById('phoneNumber').focus();
return false;
}
//validation of sign up for newsletter, checking to see if there is nothing
}
<!DOCTYPE html>
<html lang="en">
<meta charset="utf8">
<title>tester</title>
<body class="container">
<form id="pageForm" onsubmit="return checkRegistration()" action="/registration.html" method="get">
<label for="userName">Username:</label><label2 id="userNameWarning"></label2>
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<!--<span class="error" id="userName"></span><br><br>-->
<label for="Password">Password:
</label><label2 id="passwordWarning"></label2>
<input type="password" name="password" id="password" placeholder="Enter your Password" />
<!--<span class="error" id="password"></span><br><br>-->
<label for="passwordVerify">Verify your Password:
</label><label2 id="passwordVerifyWarning"></label2>
<input type="password" name="passwordVerify" id="passwordVerify" placeholder="Enter in your Password again" />
<!--<span class="error" id="passwordVerify"></span><br><br>-->
<label for="firstName">First Name:
</label><label2 id="firstNameWarning"></label2>
<input type="text" name="firstName" id = "firstName" placeholder="Enter your First Name" />
<!--<span class="error" id="firstName"></span><br><br>-->
<label for="hostName">Last Name:
</label><label2 id="lastNameWarning"></label2>
<input type="text" name="lastName" id= "lastName" placeholder="Enter your Last Name" />
<!--<span class="error" id="lastName"></span><br><br>-->
<label for="email">Email:
</label><label2 id="emailWarning"></label2>
<input type="text" name="email" id="email" placeholder="Enter your Email Address" />
<!--<span class="error" id="email"></span><br><br>-->
<label for="phoneNumber">Phone Number:
</label><label2 id="phoneNumberWarning"></label2>
<input type="text" name="phoneNumber" id = "phoneNumber" placeholder="Enter your Phone Number" />
<!--<span class="error" id="phoneNumber"></span><br><br>-->
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked > Yes
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" value="No"> No
<!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
<!-- Creation of submit button-->
<input type="submit" value="Submit" formaction=confirm.html>
</form></body>
<script src="app.js"></script>

Problems with form validation. Javascript/HTML

I'm having trouble with my form validation logic in my year one Javascript project.
Specifically with my errors reporting with the events.
The page randomly refreshes when I'm testing for "no username entered" etc.
Some errors will display for a moment and disappear.
Any help would be much appreciated, and will contribute to fixing the overall problem.
<body onload="setup()">
<div class="container-fluid">
<div class="page-header" class = "row">
<div class="col-lg-12">
<img id="banner" src = "pictures/homepage/banner.jpg" width = "100%" height = "20%"></img>
</div>
<p id="charc">Charcoal</p>
</div>
<div class="butts">
<button onclick="dropdown()" class="button">Categories</button>
<button class="button">My Account</button>
<button class="button">Shopping Cart</button>
<button id="loggedIn-Out" class="button">Login/Register</button>
</div>
<div id="myDropDwn" class= "dropContent">
womens
mens
shoes
accessories
</div>
</div>
<div class="login-page" class="col-lg-6">
<div class="form">
<form id="logForm" class="login-form">
<input id="username" type="text" placeholder="Username">
<div id="login-user-error" class="errorReps"></div>
<input id="password" type="password" placeholder="Password">
<div id="login-pass-error" class="errorReps"></div>
<button onclick="loginUser()">Login</button>
<div id="login-error" class="errorReps"></div>
<p class="loginMessage"> Not Registered? Register
<br>
<br>
Logout
</form>
<form id="regForm" class="register-form">
<input id="newFName" type="text" placeholder="First Name">
<div id="reg-FName-error" class="errorReps"></div>
<input id="newLName" type="text" placeholder="Last Name">
<div id="reg-LName-error" class="errorReps"></div>
<input id="newUName" type="text" placeholder="Username">
<div id="reg-UName-error" class="errorReps"></div>
<input id="newPass" type="password" placeholder="Password">
<div id="reg-pass-error" class="errorReps"></div>
<div id="passStrength"></div>
<input id="newEmail" type="email" placeholder="Email">
<div id="reg-email-error" class="errorReps"></div>
<input id="newPhone" type="number" placeholder="Tel. Number">
<div id="reg-phone-error" class="errorReps"></div>
<button onclick="registerUser()">Create</button>
<p class="loginMessage"> Already Registered? Login
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('.loginMessage a').click(function(){
$('form').animate({height:"toggle", opacity: "toggle"}, "slow");
});
</script>
<script>
// pre-coded users
var existingUsers =
[
{
firstname: "Gerry",
lastname: "Agnew",
username: "GerryA",
password: "password123",
email: "gerry#gmit.ie",
phone:"0833333333"
},
{
firstname: "Sean",
lastname: "Duignan",
username: "SeanD",
password: "password456",
email: "sean#gmit.ie",
phone:"0822222222"
},
{
firstname: "Michael",
lastname: "Duignan",
username: "MichaelD",
password: "password789",
email: "michael#gmit.ie",
phone:"0844444444"
}
]
//function setup()
//{
// setup functions
//}
function dropdown()
{
document.getElementById("myDropDwn").classList.toggle("show");
}
username.addEventListener('blur', logUserVerify, true);
password.addEventListener('blur', logPassVerify, true);
newFName.addEventListener('blur', fNameVerify, true);
newLName.addEventListener('blur', lNameVerify, true);
newUName.addEventListener('blur', regUserVerify, true);
newPass.addEventListener('blur', regPassVerify, true);
newEmail.addEventListener('blur', emailVerify, true);
newPhone.addEventListener('blur', phoneVerify, true);
function loginValidate()
{
if(username == "")
{
document.getElementById("login-user-error").innerHTML = "Username required";
//username.focus();
return false;
}
if(password == "")
{
document.getElementById("login-pass-error").innerHTML = "Password required";
password.focus();
return false;
}
}
function registerValidate()
{
if(registerFName == "")
{
document.getElementById("reg-FName-error").innerHTML = "First Name required";
newFName.focus();
return false;
}
if(registerLName == "")
{
document.getElementById("reg-LName-error").innerHTML = "Last Name required";
newLName.focus();
return false;
}
if(registerUName == "")
{
document.getElementById("reg-UName-error").innerHTML = "Username required";
newUName.focus();
return false;
}
if(registerUName.length < 8)
{
document.getElementById("reg-UName-error").innerHTML = "Username must be 8 characters or more";
newUName.focus();
return false;
}
if(registerPass == "")
{
document.getElementById("reg-pass-error").innerHTML = "Password required";
newPass.focus();
return false;
}
if(registerEmail == "")
{
document.getElementById("reg-email-error").innerHTML = "Email required";
newEmail.focus();
return false;
}
if(registerPhone == "")
{
document.getElementById("reg-phone-error").innerHTML = "Phone number required";
newPhone.focus();
return false;
}
}
// Event Functions
function logUserVerify()
{
if (username != "")
{
document.getElementById("login-user-error").innerHTML = "";
return true;
}
}
function logPassVerify()
{
if (password != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function fNameVerify()
{
if (registerFName != "")
{
document.getElementById("login-FName-error").innerHTML = "";
return true;
}
}
function lNameVerify()
{
if (registerLName != "")
{
document.getElementById("login-LName-error").innerHTML = "";
return true;
}
}
function regUserVerify()
{
if (registerUName != "")
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
if (registerUName > 8)
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
}
function regPassVerify()
{
if (registerPass != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function phoneVerify()
{
if (registerPhone != "")
{
document.getElementById("login-phone-error").innerHTML = "";
return true;
}
}
function emailVerify()
{
if (registerEmail != "")
{
document.getElementById("login-email-error").innerHTML = "";
return true;
}
}
// Login/Register Functions
function loginUser()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (i = 0; i < existingUsers.length; i++)
{
if(username == existingUsers[i].username && password == existingUsers[i].password)
{
alert(username + " Is logged in");
document.getElementById("loggedIn-Out").innerHTML = username;
document.getElementById("login-user-error").innerHTML = "";
localStorage.user = username;
localStorage.pass = password;
return;
}
else if(username != existingUsers[i].username)
{
document.getElementById("login-user-error").innerHTML = "Invalid, user does not exist";
username.focus();
return false;
}
else
{
loginValidate();
}
}
}
function logoutUser()
{
localStorage.removeItem("user");
localStorage.removeItem("pass");
document.getElementById("loggedIn-Out").innerHTML = "Login/Register";
}
function registerUser()
{
var registerFName = document.getElementById("newFName").value;
var registerLName = document.getElementById("newLName").value;
var registerUName = document.getElementById("newUName").value;
var registerPass = document.getElementById("newPass").value;
var registerEmail = document.getElementById("newEmail").value;
var registerPhone = document.getElementById("newPhone").value;
localStorage.regFname = registerFName;
localStorage.regLname = registerLName;
localStorage.regUname = registerUName;
localStorage.regPass = registerPass;
localStorage.regMail = registerEmail;
localStorage.regPhone = registerPhone;
var newUser =
{
firstname: registerFName,
lastname: registerLName,
username: registerUName,
password: registerPass,
email: registerEmail,
phone: registerPhone
}
for(i = 0; i < existingUsers.length; i++)
{
if(registerUName == existingUsers[i].username)
{
document.getElementById("reg-UName-error").innerHTML = "Username already exists";
newUName.focus();
return false;
}
if(registerEmail == existingUsers[i].email)
{
document.getElementById("reg-email-error").innerHTML = "Email already exists";
newEmail.focus();
return false;
}
registerValidate();
}
existingUsers.push(newUser);
}
// Password Strength functions
function passwordStr()
{
var passValue = document.getElementById("newPass").value;
if(passValue.length >= 8 && passValue.length <= 10)
{
document.getElementById("passStrength").innerHTML = "Weak";
}
else if(passValue.length > 10 && passValue.length <= 16)
{
document.getElementById("passStrength").innerHTML = "Average";
document.getElementById("passStrength").style.color = "yellow";
}
else if(passValue.length > 16)
{
document.getElementById("passStrength").innerHTML = "Strong";
document.getElementById("passStrength").style.color = "green";
}
else
{
document.getElementById("passStrength").style.color = "red";
}
}
var passInput = document.getElementById("newPass");
passInput.addEventListener("input", passwordStr);
</script>
Add a type attribute to your login button. type="button"
<button type="button" onclick="loginUser()">Login</button>
Without specifying a type, the button will default to submit behavior. You seem to be handling the login without default form submission, so setting the type to button just changes it to a regular button hence no form submission.

Javascript code won't work on my form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a form but my form is not working whenever I press submit. I am trying to evaluate whether sections of the form is empty, the email, and the number of digits for a user id. When I press submit nothing happens and I have been stuck like this for a while. FYI I have to use plain js and html.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Student Login Form</title>
<link rel='stylesheet' href='studentform.css' type='text/css' />
<script src="studentform.js"></script>
</head>
<body onload="document.form.studentid.focus();">
<h1>Student Login</h1>
<div class="container">
<form name="form" onsubmit="return validate();">
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
`
Js.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(nameEmpty(name))
{
if(studentidEmpty(studentid))
{
if(emailEmpty(email))
{
if(digitCheck(studentid))
{
if checkEmail(email)
{
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid){
if ( studentid == "" ){
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name){
if ( name == "" ){
alert("Please provide your name!");
name.focus() ;
return false;
}
}
function emailEmpty(email){
if( email == "" ){
alert( "Please provide your email!" );
email.focus();
return false;
}
function digitCheck(studentid){
var ok = studentid.search(".{8,}");
if (ok!=0){
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid){
var personList = [["Joe",11111111],["Tammy",22222222],["Jones",33333333]];
for (list in personList) {
if (name in list && studentid in list){
alert("Welcome! An email verification with be sent soon.");
return true;
} else{
alert("Student Name and/or ID not found in records");
return false;
}
}
}
}
I think you should fix this line:
if checkEmail(email)
to
if (checkEmail(email))
you have forgotten the parentheses.
Edit:
I have completely fixed your code. Your errors:
you have forgotten to add else clauses for your field checkers, they were only returning false if the validation failed
your checking "if array contains value" was wrong, I have added a method from here
you were trying to focus on the values, not tags
you were trying to test email value from the "value of the value" not "value"
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
return verify(name, studentid);
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
document.getElementById("studentid").focus();
return false;
} else {
return true;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
document.getElementById("name").focus();
return false;
} else {
return true;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
document.getElementById("email").focus();
return false;
} else {
return true;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
} else {
return true;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
return false;
} else {
return true;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (contains.call(list, name) && contains.call(list, studentid)) {
alert("Welcome! An email verification with be sent soon.");
return true;
}
}
alert("Student Name and/or ID not found in records");
return false;
}
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
<div>
<form>
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input onclick="return validate();" type="submit" name="submit" value="Submit" />
</form>
</div>
Validate function always return false !! It shouldn't.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
return nameEmpty(name) && studentidEmpty(studentid) && emailEmpty(email) && digitCheck(studentid) && checkEmail(email) && verify(name, studentid);
}
Then be sure your form looks like :
<form name="form" onsubmit="return validate();" action="javascript:void(0)">
</form>
And your autofocus input to look like :
<input type="number" name="studentid" maxlength="8" id="studentid" required autofocus/>
You're forgetting the parentheses.
It is also wrong to start and end each function, try using the code below with these corrections.
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
name.focus();
return false;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
email.focus();
return false;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (name in list && studentid in list) {
alert("Welcome! An email verification with be sent soon.");
return true;
} else {
alert("Student Name and/or ID not found in records");
return false;
}
}
}

JavaScript validation form integratation into one

I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}

Categories