storing user input in arrays for a log in site? - javascript

i am trying to make a mock up site that will allow you to create a username and password then for it to send that array of usernames and passwords over to a log in page where you will put in a username or password and it will go threw a process of checking weather it is wright or wrong and then what to do from there. what i have realized is that when i hit the button to send the information over it will not register on the other page. may you please help me find out what i screwed up on.
here is the code for where i create the username and password:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
function createLogIn() {
var usernameArray = document.getElementById("usernameMake").value;
var paswordArray = document.getElementById("pwordMake").value;
unArray.push("usernameArray");
pwArray.push("paswordArray");
localStorage.setItem("unArray", JSON.stringify([]));
localStorage.setItem("pwArray", JSON.stringify([]));
}
</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 the code for logging in with that username and password:
<!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>

In function for create login you:
You use undefined arrays unArray and pwArray
You push to this arrays string but not value of variables
You save to local storage empty array.

Related

Razor and JS Trouble: Check If User Exists

What am I doing wrong? I am trying to verify that a user does not exist. I cannot figure out how to send #email1 or #0. I tried it several ways. I can get it to work when I hard code the WHERE CLAUSE. For example, an email I know exists is doug#fresh.com. This works: "var userCheck = "SELECT * FROM USR WHERE EMAIL = 'doug#fresh.com'".Count()
These do not work: I have tried var userCheck = "SELECT * FROM USR WHERE EMAIL = " +email1.Count(); and "var userCheck = "SELECT * FROM USR WHERE EMAIL = #0".Count()
Do I have to pass email1 as a parameter???
ASP.NET- Razor:
#{
Page.Title = "Register";
var minPass = 2;
var maxPass = 100;
var email1 = "";
var pass1 = "";
var db = Database.Open("Resume");
var userCheck = "SELECT * FROM USR WHERE EMAIL = " +email1;
var userInsert = "INSERT INTO USR (EMAIL, PSWD) VALUES (#0, #1)";
if(IsPost) {
email1 = Request.Form["email1"];
pass1 = Request.Form["pass1"];
db.Execute(userInsert, email1, pass1);
Response.Redirect("~/Default");
}
}
Javascript:
var error = "";
var email1 = document.getElementById('em100').value;
var email2 = document.getElementById('em101').value;
var pass1 = document.getElementById('pw100').value;
var pass2 = document.getElementById('pw101').value;
if (#userCheck > 0) error += "</br>Email already exists."; // ?????????????????
if (!document.getElementById('em100').checkValidity()) error += "</br>Emails are not valid.";
if (email1 !== email2) error += "</br>Emails do not match.";
if (pass1 !== pass2) error += "</br>Passwords do not match.";
if (pass1.length < minPass || pass1.length > maxPass) error += "</br>Password must be minPass - maxPass characters.";
I want to comment that my approach was entirely wrong.
I am no longer using Javascript for validation, but only ASP.NET Razor.
For those who are struggling with a similar thing, below is my solution:
Be sure to include WebSecurity.InitializeDatabaseConnection("ResumeLink", "UserProfile", "UserId", "Email", true);
#{
var username = "";
var password = "";
var confirmPassword = "";
var regMsg = "";
var minPass = 2;
var maxPass = 5;
if (!IsPost) {
if (WebSecurity.IsAuthenticated) {
regMsg = String.Format("You are already logged in. (User name: {0})", WebSecurity.CurrentUserName);
}
}
if (IsPost){
WebSecurity.Logout();
username = Request["username"];
password = Request["password"];
confirmPassword = Request["confirmPassword"];
try {
var mail = new System.Net.Mail.MailAddress(username);
} catch {
regMsg += "Invalid email format.";
}
//Validation.Add("username", Validator.Regex(#"^[A-Za-z0-9._%+-]+##[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", regMsg += "Invalid email format."));
if (password != confirmPassword) {regMsg += "</br>Passwords don't match.";}
if (WebSecurity.UserExists(username)) {regMsg += String.Format("</br>User '{0}' already exists.", username);}
if (password.Length < minPass || password.Length > maxPass) {regMsg += "</br>Password doesn't meet length requirement.";}
if (regMsg == "") {
WebSecurity.CreateUserAndAccount(username,password,null,false);
regMsg = String.Format("{0} created.", username);
Response.Write("Registration Successful!");
Response.Redirect("~/Default.cshtml");
}
}
}
<style>header {visibility: hidden;}</style>
<body>
<div>
<h1>Register</h1>
<form method="post">
<p>
#if(regMsg != ""){
<span class="errorMessage">#Html.Raw(regMsg)</span>
}
</p>
<p>
<label for="username">Email Address:</label><br/>
<input type="text" name="username" id="username" value='#Request["username"]' />
</p>
<p>
<label for="password">Password #minPass-#maxPass Characters:</label><br/>
<input type="password" name="password" id="password" value="" />
</p>
<p>
<label for="confirmPassword">Confirm Password:</label><br/>
<input type="password" name="confirmPassword" id="confirmPassword" value="" />
</p>
<p>
<input type="submit" value="Submit" />
<input type="button" value="Cancel" onclick="javascript:location.href='Default.cshtml'" />
</p>
<p>
</p>
</form>
</div>
</body>

Alert input form

I want to make an alert for form input caharcter that depends on the datatype,
when I type the wrong input, the alert is showed like this
<head>
<script type="text/javascript">
function check_field(id) {
var field = document.getElementById(id);
var d = document.getElementById('plus');
if (isNaN(field.value)) {
d.innerHTML += "Is not number";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="t_field" onchange="check_field('t_field');"/><b id='plus'></b><br>
<input type="text"/>
</form>
</body>
When I try to delete the input character the alert is still showed, I want the alert change to another alert otherwise it dissapear from the screen.
the problem above is solved but there is one problem anymore
loop
do you understand what i mean?
Add an else block to handle when it is a right input.
if (isNaN(field.value))
{
d.innerHTML = "Is not number";
}
else
{
d.innerHTML = "";
}
<head>
<script type="text/javascript">
function check_field(id) {
var field = document.getElementById(id);
var d = document.getElementById('plus');
if (isNaN(field.value)) {
d.innerHTML = "Is not number";
}
else
{
d.innerHTML = "";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="t_field" onchange="check_field('t_field');"/><b id='plus'></b>
</form>
</body>
function check_field(id) {
var field = document.getElementById(id);
var d = document.getElementById('plus');
if (isNaN(field.value)) {
d.innerHTML = "Is not number";
} else {
d.innerHTML = "";
}
}
<head>
</head>
<body>
<form>
<input type="text" id="t_field" onkeyup="check_field('t_field');"/><b id='plus'></b><br>
<input type="text"/>
</form>
</body>
Please minimise your code like below
<head>
<script type="text/javascript">
function check_field(id) {
var d = document.getElementById('plus');
if (isNaN(id.value)) {
d.innerHTML = "Is not number";
}
else
{
d.innerHTML = "";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="t_field" onchange="check_field(this);"/><b id='plus'></b><br>
<input type="text"/>
</form>
</body>

to alert user if user enters other than a valid number value in each text fields and to alert user enter number if any textfield is left blank [duplicate]

This question already has answers here:
Check if input is number or letter javascript
(11 answers)
Closed 8 years ago.
<!DOCTYPE html>
<html>
<body bgcolor = "eeeeee">
<p> Add Section </p>
<label>Fir No :</label>
<input id="txt1" type="text"/></br></br>
<label>Sec No :</label>
<input id="txt2" type="text"/></br></br>
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
<!-- addition of two numbers-->
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
i have written a code in this code i am not able to alert user if he enters other than number and also how to alert the user if he left blank without filling value in addition
Try below code:
<!DOCTYPE html>
<html>
<body bgcolor = "eeeeee">
<p> Add Section </p>
<label>Fir No :</label>
<input id="txt1" type="text"/></br></br>
<label>Sec No :</label>
<input id="txt2" type="text"/></br></br>
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
<!-- addition of two numbers-->
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
if (a == "" || b == "")
{
alert('Please enter any number');
return;
}
if (isNaN(a) || isNaN(b))
{
alert('Please enter any number');
return;
}
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
Use the isNaN() to check for valid number.
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
if(a == "")
{
alert("enter txt1 value");
return;
}
if(b == ""){
alert("enter txt2 value");
return;}
if(isNaN(a)){
alert("enter valid number txt1 value");
return;}
if(isNaN(b)){
alert("enter valid number txt2 value");
return;}
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}

Array value not accesible in another function in javascript

I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.

javascript validate form check - echo out errors in form?

i have currently got a javascript code which validates my form and shows an error if a field is not completed. i also want to know how i could echo out the errors in the form so for instance if 'fname' is not filled in then this says 'You did not fill in fname' or if 'fname' and fcompany' are not filled in this says
You did not fill in fname
you did not fill in fcompany
Heres my html:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Company Name: <input type="text" name="fname">
Company Registration Number: <input type="text" name="fcompany">
heres my javascript:
<script>
function validateForm()
{
var x=document.forms["myForm"]["cname"].value;
if (x==null || x=="")
{
document.body.scrollTop = document.documentElement.scrollTop = 0;
document.getElementById("alertBox").style.display='block';
return false;
}
}
</script>
Have your validate function build an array of errors, then have another function take the errors array and build the HTML:
http://jsfiddle.net/J9LJj/
function displayErrors(errors){
var container = document.getElementById("alertBox");
var html = "<ul>";
for(var i=0; i<errors.length; i++){
html += "<li>" + errors[i] + "</li>";
}
html += "</ul>";
container.innerHTML = html;
container.style.display = "block";
}
function validateForm(){
var fname = document.forms["myForm"]["fname"].value;
var fcompany= document.forms["myForm"]["fcompany"].value;
var errors = [];
if(fname == ""){
errors.push("you did not fill in fname");
}
if(fcompany == ""){
errors.push("you did not fill in fcompany");
}
if(errors.length > 0){
displayErrors(errors);
return false;
} else {
return true;
}
}

Categories

Resources