Uncaught ReferenceError: username is not defined - javascript

Uncaught ReferenceError: username is not defined at register.html?username=Petra+Meier&email=petra%40meier.de&password=1234598&repeat_password=123459:126 (anonym) # register.html?username=Petra+Meier&email=petra%40meier.de&password=1234598&repeat_password=123459:126
The problem is within data
$.ajax({
method: "POST",
url: "p.php",
data: {
signUp_username: username,
signUp_email: email,
signUp_pass: password,
pass_again: password_proof
}
#import url('https://fonts.googleapis.com/css?family=Montserrat:400,800');
$('#switch_login').click(function() {
location.href = "http://localhost/Manage/dujic/login_3.html?#";
});
$('#register').click(function() {
$debug = false;
username = $('#signUp_username').val();
console.log(username);
email = $('#signUp_email').val();
console.log(email);
password = $('#signUp_pass').val();
console.log(password);
repeat_password = $('#pass_again').val();
console.log(repeat_password);
//1
if (!isUsername(username)) {
if ($debug)
displayMessageBox('#message', 'Bitte gültige Username eintragen!');
$('#signUp_username').focus();
$('#signUp_username').css('background-color:red');
return;
}
//2
if (!isEmail(email)) {
if ($debug)
displayMessageBox('#message', 'Bitte gültige E-Mail eintragen!');
$('#signUp_email').focus();
$('#signUp_email').css('background-color:red');
return;
}
//3
if (!isPassword(password)) {
if ($debug)
displayMessageBox('#message', 'Bitte gültiges Kennwort eintragen!');
$('#signUp_pass').focus();
$('#signUp_pass').css('background-color:red');
return;
}
//4
if (!isPassword_proof(password_proof)) {
if ($debug)
displayMessageBox('#message', 'Bitte gültiges Kennwort eintragen!');
$('#pass_again').focus();
$('#pass_again').css('background-color:red');
return;
}
if (isUsername(username) && isEmail(email) && isPassword(password) && isPassword_proof(repeat_password)) {
if ($debug)
displayMessageBox('#message', '');
$('#signUp_username').css('background-color', 'white');
$('#signUp_email').css('background-color', 'white');
$('#signUp_pass').css('background-color', 'white');
$('#pass_again').css('background-color', 'white');
if ($('#message').is(":visible")) {
$('#message').toggle();
}
}
})
$.ajax({
method: "POST",
url: "p.php",
data: {
signUp_username: username,
signUp_email: email,
signUp_pass: password,
pass_again: password_proof
}
}).done(function(msg) {
if ($debug) displayMessageBox('#message', msg);
if (msg == true) {
location.href = 'http://localhost/Manage/login_3.html?#';
} else {
displayMessageBox('#message', 'Sign In failed');
}
});
function isUsername(username) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(username);
}
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
function isPassword(password) {
if (password == "" || password.length < 4) {
return false;
} else {
var regex = /[A-Za-z0-9_]/;
return regex.test(password);
}
}
function isPassword_proof(password_proof) {
if (password == "" || password.length < 4) {
return false;
} else {
var regex = /[A-Za-z0-9_]/;
return regex.test(password);
}
}
function displayMessageBox(boxName, BoxContent) {
if ($(boxName).is(':hidden')) {
$(boxName).toggle();
}
$(boxName).text(BoxContent);
}

declare username, email... etc outside the function.
then use: username = $('#signUp_username').val(); inside

var username = $('#signUp_username').val();console.log(username);
var email = $('#signUp_email').val(); console.log(email);
var password = $('#signUp_pass').val();console.log(password);
var repeat_password = $('#pass_again').val();console.log(repeat_password);
<input type ="text" name="username" placeholder="Username" id="signUp_username" />
<input type ="email" name="email" placeholder="Email" id="signUp_email" />
<input type="password" name="password" placeholder="Password" id="signUp_pass" />
<input type="password" name="repeat_password" placeholder="Password_proof" id="pass_again" />

Related

How do i return two alerts in JS?

I wrote this code for validate password and i need to show user two different alerts.
(pw.length < 8) when this condition executed "Password need minimum 8 characters"
(pw != cpw) "Passwords does not match"
I already tried all if statements but it not gonna help.
<script>
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8)||(pw != cpw))
{
alert("please enter the correct password")
return false;
Event.preventDefault();
}
return true;
}
</script>
Does anyone know if something...
Use a boolean and two if statements. Return the boolean at the end for true or false.
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
let isValid = true;
if (pw.length < 8) {
alert('Password is not long enough. Minimum length is 8 characters.');
isValid = false;
}
if(pw !== cpw)) {
alert('Passwords do not match'.);
isValid = false;
}
return isValid;
}
Or have both messages in one alert using an array
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
const errors = [];
if (pw.length < 8) {
errors.push('Password is not long enough. Minimum length is 8 characters.');
}
if(pw !== cpw)) {
errors.push('Passwords do not match.');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
}
here is most basic version you can use this type of code.
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8))
{
alert("please enter the correct password")
return false;
} else if((cpw != pw)) {
alert("Passwords does not match")
} else {
alert("Password is correct!")
return true;
}
}
<form id="form">
<input type="text" id="txtPassword">
<input type="text" id="txtCPassword">
<input onclick="event.preventDefault();validatePassword()" type="submit" value="Submit">
</form>
This will do.
<script>
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
function validatePassword(){
if(pw.length < 8)
{
alert("Password need minimum 8 characters")
}
if(pw != cpw){
alert("Passwords does not match")
}
}
I don't think you need to show 2 alerts. When txtPassword is invalid, users have to retype both passwords whether passwords match or not. There is no point in showing "Passwords does not match" message in that case.
To know how to show 2 alerts, see my second code.
First, here is another solution:
const FORM = document.querySelector('#form');
const PSW = document.querySelector('#txtPassword');
const C_PSW = document.querySelector('#txtCPassword');
FORM.addEventListener('submit', event => {
event.preventDefault();
if (!validatePassword()) return;
console.log('Submitted');
})
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
<form action="" id="form">
<input type="password" id="txtPassword">
<input type="password" id="txtCPassword">
<input type="submit" value="Submit">
</form>
To show 2 alerts:
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
if (pw !== cpw) {
alert('Passwords does not match');
}
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}

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 validation with email check

when email are already existed, validation is hit the form action redirect the
page.i wanted to if email and all field are right way then hit the action part.
ajax success function not to return properly.
<script language="javascript">
function validate()
{
var str = true;
document.getElementById("msg1").innerHTML = "";
document.getElementById("msg2").innerHTML = "";
document.getElementById("msg3").innerHTML = "";
document.getElementById("msg4").innerHTML = "";
document.getElementById("msg5").innerHTML = "";
document.getElementById("msg6").innerHTML = "";
document.getElementById("msg7").innerHTML = "";
document.getElementById("msg8").innerHTML = "";
document.getElementById("msg9").innerHTML = "";
document.getElementById("msg10").innerHTML = "";
document.getElementById("msg11").innerHTML = "";
if (!document.frm.firstname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.firstname.value.match(patterns))
{
document.getElementById("msg1").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg1").innerHTML = "Please Enter First Name";
str = false;
}
if (!document.frm.lastname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.lastname.value.match(patterns))
{
document.getElementById("msg2").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg2").innerHTML = "Please Enter Last Name";
str = false;
}
if (document.frm.password.value == '')
{
document.getElementById("msg4").innerHTML = "Please Enter Password";
str = false;
}
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!document.frm.phone.value.match(phoneno))
{
document.getElementById("msg5").innerHTML = "Please Enter 10 Digits Mobiles";
str = false;
}
if (document.frm.country.value == '')
{
document.getElementById("msg6").innerHTML = "Please Enter Country";
str = false;
}
if (document.frm.state.value == '')
{
document.getElementById("msg7").innerHTML = "Please Enter State";
str = false;
}
if (document.frm.city.value == '')
{
document.getElementById("msg8").innerHTML = "Please Enter City";
str = false;
}
if (document.frm.address.value == '')
{
document.getElementById("msg9").innerHTML = "Please Enter Address";
str = false;
}
if (document.frm.industry.value == '')
{
document.getElementById("msg10").innerHTML = "Please Select Industry";
str = false;
}
if (document.frm.company.value == '')
{
document.getElementById("msg11").innerHTML = "Please Enter Company Name";
str = false;
}
if (!document.frm.email.value == '')
{
var validate_char = /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\#(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/;
if (!document.frm.email.value.match(validate_char))
{
document.getElementById("msg3").innerHTML = "Please Enter Valid Email ID";
str = false;
} else {
var Email = document.frm.email.value;
var datastring = 'Email=' + Email;
$.ajax({
type: "POST",
url: "client_email.php",
data: datastring,
success: function(responseText) {
if (responseText == 1)
{
$("#msg3").html("Email Is Already Exists");
str = false;
}
}
});
}
} else
{
document.getElementById("msg3").innerHTML = "Email Field Is Empty";
str = false;
}
return str;
}
</script>
Use HTML5's new type attributes to accomplish this..
For email validity write:
<input type="email" name="email" required/>
and if the email is empty or wrong manner ,it will never hit submit event..Hence will not be redirected...
For eg:https://www.w3schools.com/code/tryit.asp?filename=FNZQV8G6AJ8P
for more types:https://www.w3schools.com/html/html_form_input_types.asp
Server Side:
Form Required Every Field By PHP
Form Type Validation By PHP

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

Categories