Warning messages for form validation fields are not occurring - javascript

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>

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.

I want to match both fields but every time i run this script so ans comes in false please check my code or logic

html part :
<input type="text" id="name" placeholder="Email" />
<input type="password" id="pass" placeholder="Password" />
<button type="submit" onclick="validateUser()">Submit</button>
<p id="para"></p>
JavaScript part :
var USERS = ['sumair', 'awais', 'umair'];
var PASSWORDS = [1234, 1234, 1234]
function validateUser() {
var username = document.getElementById('name').value;
var password = document.getElementById('pass').value;
for (var i in USERS) {
if (username == USERS[i] && password == PASSWORDS[i]) {
document.getElementById('para').innerHTML = "you are in";
} else {
document.getElementById('para').innerHTML = "you are not in";
}
}
}
You need to break loop when the condition is achieved.
//Create a variable
var result = false;
for (var i in USERS) {
if (username == USERS[i] && password == PASSWORDS[i]) {
result = true;
break;
}
}
//Based on the basis of result.
if (result) {
document.getElementById('para').innerHTML = "you are in";
} else {
document.getElementById('para').innerHTML = "you are not in";
}
for (var i in USERS) {
if (username == USERS[i] && password == PASSWORDS[i]) {
document.getElementById('para').innerHTML = "you are in";
break;
} else {
document.getElementById('para').innerHTML = "you are not in";
}
}

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;
}
}

issue in my jquery form validation

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;
}

Javascript - Value not passing to function

So I have this form:
<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>
and these two functions:
function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}
if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false
if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;
return true;
}
function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}
Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?
Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:
function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var
if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

Categories