Email validation function not working properly with form button - javascript

I am working on my final project for my JS class. I have reached a bit of a roadblock, and was hoping for a little guidance.
I am looking to take the input (all coding needs to be done in JS) for email and validate. If the email is validated, then it should send the input to be written on a new webpage. If the the input is not valid, there should be an alert and the user should then reenter a proper email address.
This is just a portion of the project. I am creating having the user enter input information for a resume to written on the new page.
With the current state of the code, it is popping up the alert box that the email is not valid (even when it is). I have gotten it write if I take away the validation portion. However, it writes "undefined".
//html
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>
//JS email
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail(inputEmail) {
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open("");
openWindow.document.write(inputEmail);
}
}
If anybody would be so kind as to advise on this issue, I would be grateful. Thank you.

The issue was simply that you were passing inputEmail as the argument to test() when what you actually want to test is inputEmail.value. Demonstration below should work:
const validateEmail = (e, inputEmail) => {
e.preventDefault();
if (/^[^\s#]+#[^\s#]+\.[^\s#]+$/.test(inputEmail.value)) {
console.log(`${inputEmail.value} is a VALID email address :)`);
return true;
}
console.log(`${inputEmail.value} is an INVALID e-mail address. Please fix!`);
return false;
};
const init = () => {
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
document.querySelector('form').addEventListener('submit', e => validateEmail(e, inputEmail));
};
init();
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src="projectJS.js"></script>
<br><br>
<form>
<input type="submit" value="Create Resume">
</form>
</body>

add .value to get Input email like this:
var testRe = re.test(inputEmail.value);

I've solved your problem. Now it's working. Check it.
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail() {
var inputEmail = document.getElementById('email').value; //get email id
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open();
openWindow.document.write(inputEmail);
}
}
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>

Related

Javascript function not working for login

I am trying to create a very simple login form that requires the user to input a password and a username. If the user does not input a username or a password then i want an alert to pop up informing the user that he needs to input a username or a password and the page will not continue on to the welcome page. however this is not working......i dont get any alert pop up and also i am redirected to the welcome page automatically after i hit 'sign in' i just dont understand what the issue is. Any help would be very much appreciated and thank you in advance.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script type = "text/javascript">
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
return false;
else
{
true;
}
}
</script>
</head>
<body>
<form onsubmit = "return validate()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>
The problem is that on the onsubmit event on the form, you are returning "validate()", which is not a real function.
Instead, replace that bit, in the onsubmit attribute, to onsubmit="return login()", since that appears to be your replacement for the validate function.
Secondly though, in the login function itself, for most browsers you also need to call event.preventDefault(), right before return false (or perhaps instead of). Also, there was a } missing in the login function, also causing an error.
The fixed code should be
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
event.preventDefault();
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
event.preventDefault();
return false;
}
else//this part is also completely extraneous,there's no reason to have it, it should work the same either way
{
true;
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form onsubmit = "return login()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>

HTML/JS code to display Error Message if Input is Wrong

I am trying to write an HTML5 - JS Program that displays an Error Message IF the User Input is Empty. But I am not able to get the "Error Message", even thou I can't seem to find any issues.
I am a complete beginner and the Video Tutorial I am using doesn't have any User Support.
Please Help.
I have tried all I know but no avail.
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
<script type="text/javascript">
function displayInput()
{
var testInput = document.getElementById("name").value;
if (testInput.lenght == 0)
{
document.getElementById("para").innerHTML = "NOOOO";
}else
document.getElementById("para").innerHTML = testInput;
}
</script>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>
</body>
</html>
If the Input is Empty an Error Message i.e NOOOO should display.
hi you made spelling mistake in length property of element
it should not be lenght
function displayInput()
{
let el = document.getElementById("name");
let para = document.getElementById("para")
var testInput = el.value;
if (testInput.length == 0)
{
para.innerHTML = "NOOOO";
}
else{
para.innerHTML = testInput;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

JavaScript array from user input sent to different page of site?

i saw this guy who had unanswered question on this site and i have been trying for the past hour to make his code work. as an amateur myself i cant seem to make the code work. the idea of the code is for you to be able to make a username and password on one page of the site. then it will send it as an array over to another page where it is processed as a log in. as i said i am an amateur and deep simple detail would be grate. thank you!
here is the page where the username and passwords are made:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
function createLogIn() {
var usernameArray = document.getElementById("usernameMake").value;
var paswordArray = document.getElementById("pwordMake").value;
var unArray = []
var pwArray = []
localStorage.setItem("unArray", JSON.stringify([]));
localStorage.setItem("pwArray", JSON.stringify([]));
unArray.push("usernameArray");
pwArray.push("paswordArray");
}
</script>
</head>
<body>
<form name = "makeLogIn">
<p class="log_on">
ENTER YOUR NEW USERNAME <input type="text" id="usernameMake"><br><br><br><br><br>
ENTER YOUR NEW PASSWORD <input type="text" id="pwordMake">
<input type="button" value="create it" id="Submit" onclick="createLogIn">
</p>
</form>
</body>
</html>
here is where the username and password that were just created are used to log in:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = JSON.parse(localStorage.getItem("unArray"));
var pwArray = JSON.parse(localStorage.getItem("pwArray"));
for (var i = 0; i < unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" id="Submit" onclick="validate()">
</p>
</form>
</body>
</html>
So you need a few things to make this happen - and there are a million ways to skin this cat.
The most simple example I can provide is using basic POST request from a form - sending that data to a form processor. The steps work as follows:
Provide a form where we can get the username and passwords input
Send that data to a processor for validation
Redirect back to the original form if the logins are invalid or on to a another page if the validation passes.
And for your validate.php file:
<?php
$password = $_POST['password']; // gets password field passed from previous page
$username = $_POST['username']; // gets username passed from previous page
if($username == 'bob' && $password == 'bobs password') {
// do whatever you want to here in the case they got it right
echo 'Username & Password are CORRECT';
} else {
// do whatever you want to do if it's wrong
header('Location:http://mywebsite.com/login.html');
}
?>

Get a value from Javascript

I want to get the value that I entered in the prompt, and save it in a variable to use it to update a DB later .. I try this but is does not work !!
#{
var fileName = "";
var db = Database.Open( "GP" );
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
<html lang="en">
<body>
<script>
function myFunction() {
newName = prompt("Please enter new file name :");
if (newName != null)
{
#fileName = newName;
}
}
</script>
</body>
</html>
JavaScript is client side language. You can't updated db with it. You can send request to your server side script, which will update something in datatable.
You can find example of doing this here or just use google.
Try this code:
$(document).ready(function() {
var fileName = '';
var newName = prompt('Please enter a new file name');
if(newName != null) {
fileName = newName;
console.log(fileName);
}
});
Its getting the value you entered through javascript.
Demo here
From your question is not clear what is your goal.
If you want to store a value in your page waiting to use it when the page is posted, you could use a hidden input field.
In my example the value inputed when the page is loaded is stored until the user clicks the submit button:
#{
if(IsPost){
var fileName = Request["fileName"];
var db = Database.Open("GP");
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
}
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form method="post">
<input type="hidden" name="fileName" id="fileName" value="" />
<input type="submit" />
</form>
<script>
$(document).ready(function () {
var newName = prompt('Please enter a new file name');
$('#fileName').val(newName);
});
</script>
</body>
</html>
Else, if you want to update your database without submitting your page, you should use Ajax. This article could help you: Posting Data With jQuery AJAX In ASP.NET Razor Web Pages.

Categories

Resources