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.
Related
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" />
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;
}
}
}
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";
}
}
My html code sends the request to php to send email. In my case the email can be sent in Google Chrome & Edge but not in Firefox when I set the button type=submit, when I change type=button, it works fine. My javascript code is:
function Send() {
var allset = true;
var namevalid = true;
var emailvalid = false;
var commentvalid = false;
var sent = 0;
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if ($("#email").val() == '' || $("#email").val() == null) {
$("#email").addClass("invalid");
allset = false;
}
else {
if (!$("#email").val().match(emailPattern)) {
$("#email").removeClass("valid");
$("#email").addClass("invalid");
allset = false;
}
else {
emailvalid = true;
$("#email").addClass("valid");
}
}
if ($("#comment").val() == '' || $("#comment").val() == null) {
$("#comment").addClass("invalid");
allset = false;
}
else {
commentvalid = true;
$("#comment").addClass("valid");
}
$("#name").addClass("valid");
if (namevalid === true && emailvalid === true && commentvalid === true) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var demo = document.getElementById("sel1").value;
var comment = document.getElementById("comment").value;
alert("Request Successfully Received");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText)
}
};
sent = 1;
xhttp.open("POST", "email.php?" + "name=" + name + "&mail=" + email + "&phone=" + number + "&msg=" + comment + "&demo=" + demo, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
else
{
alert("Please fill all the fields correctly");
}
}
My html for form's button is:
<form class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />
</p>
<p class="number">
<input type="text" name="telephone" maxlength="30" class="feedback-input" size="30" id="number" placeholder="Number">
</p>
<p class="number" id="demotype">
<select class="form-control feedback-input demotype" id="sel1" name="demo">
<option> something </option>
</select>
</p>
<p class="text">
<textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
</p>
<div class="submit">
<input type="submit" id="button-blue" onclick="Send()" value="Send" />
<div class="ease"></div>
</div>
</form>
'type=submit' is basically for submitting forms and 'type=button' is just a button to be bind with some functions. If you don't have any form as its parent element and an error occurs when you click the button, I suggest you to use 'type=button' instead.
Just add return false; at the end of function becuase submit button submits your form. Like this.
function Send() {
var allset = true;
var namevalid = true;
var emailvalid = false;
var commentvalid = false;
var sent=0;
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if ($("#email").val() == '' || $("#email").val() == null) {
$("#email").addClass("invalid");
allset = false;
}
else {
if (!$("#email").val().match(emailPattern)) {
$("#email").removeClass("valid");
$("#email").addClass("invalid");
allset = false;
}
else {
emailvalid = true;
$("#email").addClass("valid");
}
}
if ($("#comment").val() == '' || $("#comment").val() == null) {
$("#comment").addClass("invalid");
allset = false;
}
else {
commentvalid = true;
$("#comment").addClass("valid");
}
$("#name").addClass("valid");
if (namevalid === true && emailvalid === true && commentvalid === true) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
var demo=document.getElementById("sel1").value;
var comment = document.getElementById("comment").value;
alert("Request Successfully Received");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText)
}
};
sent=1;
xhttp.open("POST", "email.php?"+"name="+name+"&mail="+email+"&phone="+number+"&msg="+comment+"&demo="+demo, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
else
{
alert("Please fill all the fields correctly");
}
return false;
}
<div id="form">
<form method="post" action="register1.aspx" onsubmit="return validateForm();"name="register1" >
<h1>
Register to exess the site</h1>
<input type="text" name="firstname" class=" br"/>
<em>First name</em><br />
<span id="firstnmsg"></span><br />
<input type="text" name="lastname" class=" br" /><em>Last name</em><br />
<span id="lastnmsg"></span><br />
<input type="text" name="username" class=" br" /><em>username</em><br>
<span id="usermsg"></span><br />
<input type="password" name="password" class=" br" /><em>password</em><br />
<input type="password"name="password1" class=" br" /><em>Confirm password</em>
<span id="pass1msg"></span><br />
<input type="text" name="email" class=" br"/><em>Email!</em><br />
<span id="emailmsg"></span><br />
<select name="sex">
<option>Please select a Gender</option>
<option>Male</option>
<option>Female</option>
<em>Gender</em>
</select><br />
<input type="submit" name="submit" value="Register " onclick="return validateForm();" />
<input type="reset" name="reset" value="Reset" onclick="return resetMsg();"/>
</form>
<span> <%=Session["regstatus"] %></span>
</div>
<div id="log_in">
<h1><em>log in</em></h1>
<form action="WebForm2.aspx"method="post" name="log_in" onsubmit="return validateloginform"><br />
<span id="usernamemsg"><%=Session["usernamemsg"] %> </span><input type="text" name="username_1" class="br" /><em>Username</em><br />
<span id="passwordmsg"><%=Session ["passwordmsg"] %></span><input type="password" name="password_1" class="br" /><em>Password</em><br />
<input type="submit" name="submit2" onclick=" validateloginform"/>
</form>
</div>
<script type="text/javascript">
function isEmpty(str) {
return (str.length == 0);
}
function isNumeric(str) {
var c = true;
for (var i = 0; i < str.length; i++) {
c = !(isNaN(str[i]));
}
return c;
}
function isValid(str) {
var badChar = "\\;:!##$%^&*()-_=+`~<>?[]{}|/,.";
for (var l = 0; l < str.length; l++) {
for (var c = 0; c < badChar.length; c++) {
if (str[l] == badChar[c]) {
return true;
}
if (str[l] == " " || str[l] == "\"" || str[l] == "\'") {
return true;
}
}
}
return false;
}
function isShort(str) {
return (str.length < 3);
}
//Reset Error Messages Function -->
function resetMsg() {
document.getElementById("firstnmsg").innerHTML = "";
document.getElementById("lastnmsg").innerHTML = "";
document.getElementById("usermsg").innerHTML = "";
document.getElementById("passwordmsg").innerHTML = "";
document.getElementById("pssword1msg").innerHTML = "";
document.getElementById("emailmsg").innerHTML = "";
document.getElementById("BdateMsg").innerHTML = "";
document.getElementById("UnameMsg").innerHTML = "";
document.getElementById("PwdMsg").innerHTML = "";
document.getElementById("LoginError").innerHTML = "";
return true;
}
//Main Sign Up Form Validation Function -->
function validateForm() {
resetMsg();
var val = true;
//First Name Validation ---------------------------------------->
if (isEmpty(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.firstname.value) || isValid(signup.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Last Name Validation ------------------>
if (isEmpty(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.lastname.value) || isValid(signup.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Username Validation --------------------------------------------->
if (isEmpty(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Empty";
val = false;
}
else {
if (!isNumeric(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Use Numbers";
}
else {
if (isShort(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Too Short";
val = false;
}
}
}
//Password Validation ----------------------------------------------->
if (isEmpty(register1.password1.value)) {
document.getElementById("Password1Msg").innerHTML = " Empty";
val = false;
}
else {
if (isValid(register1.password.value)) {
document.getElementById("Password1Msg").innerHTML = " Invalid";
}
else {
if (register1.password.value == register1.password1.value) {
if (signup.password1.value.length < 6 && signup.password1.value != "") {
document.getElementById("pass1msg").innerHTML = " Too Short";
val = false;
}
}
else {
document.getElementById("pass1msg").innerHTML = " Don't Match";
val = false;
}
}
}
//Email Validation -------------------------------------->
var EmailField = document.forms["register1"]["email"].value;
var atpos = EmailField.indexOf("#");
var dotpos = EmailField.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EmailField.length) {
document.getElementById("emailmsg").innerHTML = " Invalid Email";
val = false;
}
if (EmailField == null || EmailField == "") {
document.getElementById("emailmsg").innerHTML = " Empty";
val = false;
}
//Main Login Validation Function -->
function validateLoginForm() {
resetMsg();
var val = true;
//Username Validation
if (isEmpty(log_in.username.value)) {
document.getElementById("usernamemsg").innerHTML = " Empty";
val = false;
}
//Password Validation
if (isEmpty(log_in.password.value)) {
document.getElementById("passwordmsg").innerHTML = " Empty";
val = false;
}
return val;
}
</script>
The validations won't work and I dont know why. This is a school project.
my main problem is that the script isnt running when im submiting the form ,when there even some errors at the form(what the user submits) it still goes to the next page and no innerHtml massage is shown.
Here, I went through your code, refractored a lot of it, wrote out some comments on how to improve it.
What stops the form from submitting is returning false. You're returning a variable called val, and if there is an error that variable is set to false, thus returning false and preventing the form from submitting.
I recommend taking the JS and putting it in your text editor and reading through everything. You should learn a good bit.
Here it is: http://jsfiddle.net/2x5LU/
I just did first name cause I have to work now, but you should be able to work off of this.
function validateForm(){
resetMsg();
var val = true;
if(isEmpty(firstName.value)){
firstNameMsg = 'Empty';
val = false;
}else if(isNumeric(firstName.value)){
firstNameMsg = 'Letters Only';
val = false;
}else if(isShort(firstName.value)){
firstNameMsg = 'Too Short';
val = false;
}
return val;
}