I made 3 pages - one for Login, one for Register and one for Home. After I press the submit button, I am redirectioned to a new window. I want to be in the same window, but redirectioned to the home page, not a new tab, only one page. After the Login/Register page -> Home page. I have tried location.assign, location.reload, window.location.reload etc., but it did not work. Maybe there is something wrong in my code but I honestly dont know what. HTML and JS code for Login form:
<form name="LoginForm">
<p>Username</p>
<input type="text" name="user" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pass" placeholder="Enter Password">
<input type="submit" name="" value="Login" onclick="return redirect_home1();">
Forgot your password?<br>
Register here for a new account.
</form>
function redirect_home1() {
var x = document.forms["LoginForm"]["user"].value;
var y = document.forms["LoginForm"]["pass"].value;
if (x == "" && y == "")
alert("Must complete Username and Password");
else if (x == "" && y != "")
alert("Must complete Username");
else if (y == "" && x != "")
alert("Must complete Password.");
else {
alert("Sumbited. You will be redirected in a few seconds...");
location.assign('location.html');
}
return true;
}
You can use the window object to change your page location.
window.location.href = "filename.html"
Related
I am trying to build a login.js script that listens for the login form submit event. When I try to run my code, it's not logging in or working properly
I' working with JavaScript, which is requested to use. I built the login form in HTML and have worked on the login function within JavaScript. It can;t be inline JavaScript, it has to be a separate script from HTML.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["adrian#tissue.com",
"dduzen1#live.spcollege.edu",
"deannaduzen#gmail.com"
]
var passwordArray = ["welcome1", "w3lc0m3", "ch1c#g0"]
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Login is successful");
window.location = "index.html";
return false;
}
var again = "tries";
if (count == 1) {
again = "try"
}
if (count >= 1) {
alert("Wrong username or password")
count--;
} else {
alert("Incorrect username or password, you are now blocked");
document.login.username.value = "You are now blocked";
document.login.password.value = "You are now blocked";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<!-- start of login form -->
<div class="login-page">
<div class="form">
<form class="register-form" onsubmit="return validate() ;" method="post">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<input type="text" placeholder="email id" />
<button>Create</button>
<p class="message">Already registered? Login
</p>
</form>
<form class="login-form">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
</div>
</div>
It needs to allow the three login information I put into the code to log into the site. When logging in, it blinks as if it's doing something, but isn't going anywhere nor does it show that the person is logged in.
You are not validating correctly with the return sentence, also your onsubmit attribute was in the register form.
Use name attribute on forms
This will help you to identify your forms and inputs easily with JavaScript, otherwise you might have problems identifying which input is which in larger forms.
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
With this applied to your login form, you can reference it by doing document.login.
Take advantage over native HTML events in JavaScript
The way you are retrieving the username and password is a lot complex that it should, you can add an event listener in JavaScript and handle everything there:
const loginForm = document.login;
loginForm.addEventListener("submit", validate);
This will call validate every time the form is submitted. Also, it sends the event as a parameter, so you can receive it like this in your function:
function validate(event) {
event.preventDefault(); // Stop form redirection
let user = event.target.user.value,
pass = event.target.pass.value;
// REST OF THE CODE ...
}
This is easier since we added name attributes to the inputs, so we can identify them by user and pass.
Validation
NOTE: I do not recommend validating username:password data directly in the browser, since this is a big vulnerability and must be validated server-side.
You can simplify this validation by binding the username with its password in an object, instead of creating two arrays:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
And then, having the inputs value saved in user and pass variables, you can do:
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
//WRONG LOGIN CREDENTIALS
attempts--;
validateAttempts();
}
With the purpose of not having a lot of code in sight, you should create another function that its only job is to validate if you should block the user or not.
The result
I should mention that this will only work to validate the user form, if you need to save a session and keep an user logged in, you must use a server-side language.
I leave you a snippet with all of this changes working, see it for yourself:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
const loginForm = document.login;
let attempts = 3;
loginForm.addEventListener("submit", validate);
function validate(event) {
event.preventDefault();
let user = event.target.user.value,
pass = event.target.pass.value;
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
console.log('Wrong username or password.');
attempts--;
validateAttempts()
}
}
function validateAttempts() {
if (attempts <= 0) {
console.log("You are now blocked");
loginForm.user.value = "You are now blocked";
loginForm.pass.value = "You are now blocked";
loginForm.user.disabled = true;
loginForm.pass.disabled = true;
}
}
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>
I have a login page after being logged to page I move to my next-page (welcome).
The problem is that if I copy and paste the URL of the next-page (welcome) my page also open, I want to restrict to open the next page without login access.
Guide me What to do.
Script
function click() {
inputname = $('#name').val();
inputpassword =$('#pass').val();
for (i in data.username ) //to match username with provided array
{
name = data.username[i];
for ( i in data.password){
pass = data.password[i];
if (inputname == name & inputpassword == pass ){
window.open('welcome1.html','_self');
}
}
}
if (inputname != name & inputpassword != pass ){
alert("Wrong Password");
}
}
HTML
<input type="mail" id="name">
<input type="password" id="pass">
<input type="submit" id="submit" value="log In" onclick= "click()">
This is not a secure method of authentication. This solutions should not be on any system which you want to make secure. Authentication should happen on the server, not the client.
In your question, you never check on the second page if the user authenticated on the first page. In order to check this, you should use session storage.
// LOGIN.js
function click() {
inputname = $('#name').val();
inputpassword =$('#pass').val();
for (i in data.username ) //to match username with provided array
{
name = data.username[i];
for ( i in data.password){
pass = data.password[i];
if (inputname == name & inputpassword == pass ){
//The user has successfully authenticated. We need to store this information
//for the next page.
sessionStorage.setItem("AuthenticationState", "Authenticated");
//This authentication key will expire in 1 hour.
sessionStorage.setItem("AuthenticationExpires", Date.now.addHours(1));
//Push the user over to the next page.
window.open('welcome1.html','_self');
}
}
}
if (inputname != name & inputpassword != pass ){
alert("Wrong Password");
}
}
//addHours to a date.
//Credit to: Kennebec
//https://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
<!-- LOGIN.html --->
<input type="text" id="name" name="name" />
<input type="text" id="pass" name="pass" />
<input type="submit" id="sub" name="sub" onclick="click();" />
And then on your second page, check to see if the user is authenticated. If not, push them over to an Access Denied page.
//Is the user authenticated?
if (sessionStorage.getItem('AuthenticationState') === null) {
window.open("AccessDenied.html", "_self");
}
//Is their authentication token still valid?
else if (Date.now > new Date(sessionStorage.getItem('AuthenticationExpires'))) {
window.open("AccessDenied.html", "_self");
}
else {
//The user is authenticated and the authentication has not expired.
}
I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}
I have got a form in html that validates the user input. The problem is it takes a lot of time even on localhost to jump to the 'action' page. Heres the code
<form action="Activity.php" method="GET" >
<div style="display:none">
<input type="text" id="chapter" name="chapter"/>
<input type="text" id="book" name="book"/>
<input type="text" id="activity" name="activity"/>
</div>
<input type="image" src="includes/file.png" onClick="return validateForm()" title="Create New Activity" >
</form>
The code for validateForm is :
function validateForm()
{
document.body.style.cursor='wait';
if(document.getElementById("book").value==null || document.getElementById("book").value==""
|| document.getElementById("chapter").value==null || document.getElementById("chapter").value=="")
{
document.body.style.cursor='default';
alert("You cannot create an activity at the selected location.");
return false;
}
var name=prompt("Please enter the New Activity Name","New Activity Name");
if (name==null || name=="")
{
document.body.style.cursor='default';
return false;
}
document.getElementById('activity').value=encodeURI(name);
return true;
}
If I remove the prompt in above function, it instantly jumps to the activity.php page, but if I keep the prompt and ask the activity name, it takes a long time to load the desired page (may be cauze the form submitting process was interrupted by the prompt and on clicking the prompts 'ok' button the submission starts again!!no idea :S)what should be a solution (a fast one) to take input from a user when a form is being submitted? thanks!!
This object does not exist: document.getElementById('activity')
Try this.
function validateForm()
{
document.body.style.cursor='wait';
if(document.getElementById("book").value || document.getElementById("chapter").value)
{
document.body.style.cursor='default';
alert("You cannot create an activity at the selected location.");
return false;
}
var name=prompt("Please enter the New Activity Name","New Activity Name");
if (name)
{
document.body.style.cursor='default';
return false;
}
//document.getElementById('activity').value=encodeURI(name);
return true;
}